Difference between ArrayList and HashMap

Posted By: Matpal - June 08, 2011
an ArrayList implements the List interface and a HashMap implements the Map interface of Collection framework !
Lets understand the interfaces first-

List
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

Map:
An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

If you use an ArrayList, you have to access the elements with an index (int type). You would use an ArrayList when you want to keep things in sorted order (the order they are added, or indeed the position within the list that you specify when you add the object).
Eg

ArrayList al = new ArrayList();
    
    // add elements to the array list
    al.add("C");
    al.add("A");
    al.add("E");
    al.add("B");
    al.add("D");
    al.add("Hitesh");
   
     //ArrayList can enter anytype of datatype as we add integer here
    al.add(1, 100);
    
    // display the array list
    System.out.println("Contents of al: " + al);

The output will be

C 100 A E B D Hitesh (Note its in a sorted order)

Once can remove the value getting index like
a1.remove(2) it will remove A from the list


And with a HashMap, you can access them by an index from another type- Key (For example, a String)

Eg

HashMap hm = new HashMap();
// Put elements to the map
hm.put("John Doe", new Double(3434.34));
hm.put("Tom Smith", new Double(123.22));
hm.put("Jane Baker", new Double(1378.00));
hm.put("Todd Hall", new Double(99.22));
hm.put("Ralph Smith", new Double(-19.08));

// Get a set of the entries

Set set = hm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}

The output will be

Ralph Smith: -19.08
Tom Smith: 123.22
John Doe: 3434.34
Todd Hall: 99.22
Jane Baker: 1378.0

You should note that a hash map does not guarantee the order of its elements. Therefore, the order in which elements are added to a hash map is not necessarily the order in which they are read by an iterator.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.