In the tutorial, you will learn about the difference in HashMap and ArrayList or HashMap vs ArrayList in Java.
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
- The first difference between ArrayList and HashMap is that ArrayList implements List interface while HashMap implements Map interface in Java.
- ArrayList only stores one object while HashMap stores two objects key and value.
- 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.
- ArrayList maintains the order of object, in which they are inserted while HashMap doesn’t provide any ordering guarantee.
- 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 –
- Both ArrayList and HashMap are not synchronized, you should not use them in the multithreading environment without external synchronization.
- 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.
- Both ArrayList and HashMap allows null. HashMap allows null key and values.
- ArrayList allows duplicate elements and HashMap allow duplicate values.
- Both ArrayList and HashMap can be traversed through Iterator in Java.