Read Also : Difference between HashMap and Hashtable
Difference between HashMap and ArrayList in Java
1. Implementation : HashMap implements Map interface in Java while ArrayList implements List interface.
2. Storing objects: HashMap stores two objects key and value while ArrayList only stores one object.
3. Ordering : HashMap doesn't provide ordering guarantee while ArrayList maintains the order of the object in which they are inserted.
4. Duplicates : HashMap doesn't allow duplicate keys though it allows duplicate values while ArrayList does allows duplicates.
5. Equals and Hashcode method : The fifth difference between HashMap and ArrayList is that keys of HashMap must implement equals() and hashCode() methods while ArrayList does not have to implement such methods.
6. get() method performance : The sixth difference between HashMap and ArrayList is that HashMap get(key) method performance is O(1) in best case and O(n) in worst case while ArrayList get(index) method always gives an O(1) performance.
Example of HashMap and ArrayList in Java
import java.util.Hashtable; public class HashMapArrayListExample { public static void main(String[] args) {
ArrayList<String> arrlistobj = new ArrayList<String>();
arrlistobj.add("1. Alive is awesome"); arrlistobj.add("2. Love yourself"); System.out.println("ArrayList object output :"+ arrlistobj);
HashMaphashmapobj = new HashMap (); hashmapobj.put("Alive is ", "awesome"); hashmapobj.put("Love", "yourself"); System.out.println("HashMap object output :"+hashmapobj);
} }
Output
ArrayList object output :[1. Alive is awesome, 2. Love yourself] HashMap object output :{Love=yourself, Alive is =awesome}
Similarities between HashMap and ArrayList
1. Allows null : Both HashMap and ArrayList allows null. HashMap can have one null key and any number of null values.
2. Synchronized : Both HashMap and ArrayList are not synchronized. One needs to avoid using them in multithreading environment.
3. Traversal : Both HashMap and ArrayList can be traversed through iterator in java.
4. Iterator : Both HashMap and ArrayList classes iterator are fail-fast i.e they will throw ConcurrentModificationException as soon as they detect any structural change in ArrayList or HashMap.
Recap : Difference between HashMap and ArrayList in Java
HashMap | ArrayList | |
---|---|---|
Implementation | Map | List |
Storing Objects | two objects key and value | store only one object |
Duplicates | Unique key,duplicate values | permit duplicates |
Ordering | Unordered | Maintains order |
get() performance | Worst O(n) best O(1) | O(1) |
In case you have any other query please mention in the comments .