HashMap vs ArrayList

In the tutorial, you will learn about the difference in HashMap and ArrayList or HashMap vs ArrayList in Java.

 

HashMap and ArrayList are two different Collection class in Java. They both used to store objects but they are completely different on their implementation and working.

The main difference between ArrayList and HashMap is that ArrayList is index based data-structure backed by Array while HashMap is map data structure which works on hashing to retrieve stored values.

 

HashMap vs ArrayList

  1. The first difference between ArrayList and HashMap is that ArrayList implements List interface while HashMap implements Map interface in Java.
  2. ArrayList only stores one object while HashMap stores two objects key and value.
  3. The third difference between HashMap and ArrayList is that keys of HashMap must implement equals() and hashCode() method correctly, ArrayList doesn’t have that requirement but its good to have that because contains()  method of ArrayList will use equals() method to see if that object already exists or not.
  4. ArrayList maintains the order of object, in which they are inserted while HashMap doesn’t provide any ordering guarantee.
  5. ArrayList allows duplicates but HashMap doesn’t allow duplicates key, though it allows duplicate values.

 

Similarities between ArrayList and HashMap

We have seen the difference in HashMap and ArrayList. Now let’s see the similarities between HashMap and ArrayList –

  1. Both ArrayList and HashMap are not synchronized, you should not use them in the multithreading environment without external synchronization.
  2. Both ArrayList and HashMap Iterator are fail-fast, they will throw ConcurrentModificationException as soon as they detect any structural change in ArrayList or HashMap once Iterator is created.
  3. Both ArrayList and HashMap allows null. HashMap allows null key and values.
  4. ArrayList allows duplicate elements and HashMap allow duplicate values.
  5. Both ArrayList and HashMap can be traversed through Iterator in Java.

 

Selenium Tutorial:

If you liked this video, then please subscribe to our YouTube Channel for more video tutorials.

0 Comment

Leave a Reply