ArrayList and HashMap are two different datastructures, as you already know - an ArrayList is an ordered sequence (a list), and a HashMap is a dictionary (which contains key-value pairs, and where you can efficiently lookup the value if you know the key).
It's hard to say when you use which; for some problems, it's natural to use a list, and for other problems, it's natural to use a dictionary. You'll have to think in each situation which data structure fits best.
I Understand your point, can you give examples for ArrayList and HashMap . I say if you want to store Employee name ,in this situation i can use ArrayList . if you want to store Employee name with his salary i can use Employee name as key and salary as value . Is it correct.
only it maintains the order; that list is different from milk-flour-eggs.
A map is like an address book
Campbell ↦ 123 High St
Muhammad ↦ 987 London Rd
Rajendra ↦ 345 Station Rd
Jesper ↦ 567 Church St
Rahul ↦ 765 North St
There the name is the "key" and the address is the "value".
Rahul P Kumar
Joined: Sep 26, 2009
usually key should be immutable. String is fit for key. you can use them as key. but the problem is name can be duplicate. In map, if you will use names for key then corresponding salaries will be overriden by latest employee name in case of duplicate names. To avoid such situations you can choose to override equals method, where in case of duplicate first name, try combination of last name and so on. Don't forget to override hashcode(), if you overridden equals().
Same thing you could have achieved through list by storing value objects in it. But guess you have to search salary of employee. In list you have to iterate over whole list to compare first name or so to find your desired employee, while in map you just have to supply name of the employee, which is key and you get the corresponding salary.
Contrast this with the situation , where there are values but nothing to associate as key. You don't have to find search a particular value in the data structure, then go for list.
when you populate a table you would use an array list where you have to iterate over an entire collection or list.
hashmap is used when you are intersted with a particular value to be used from the entire collection or list.
example: you have your name in an arraylist. in order to print it you need to iterate the entire list and compare each entry.
in case of hashmap you will be having an equivalent key for your name value. instead of iterating the list you can get the value by specifying the key associated with it and only that value will be printed.
subject: when to use ArrayList and when to use HashMap