Difference between Arraylist and HashMap?
- ArrayList implements List Interface while HashMap is an implementation of Map interface.
- Memory consumption is high in HashMap compared to the ArrayList.
- ArrayList maintains the insertion order while HashMap doesn't maintain any order. ArrayList stores the elements only as value and maintain internally the indexing for every element. While HashMap stores elements with key and value pair, i.e. two objects. So HashMap takes more memory comparatively.
- ArrayList allows duplicate elements but HashMap doesn't allow duplicate keys (It does allow duplicate values)
- In ArrayList, an element can be fetched easily by specifying the index of it. But in HashMap, the elements is fetched by its corresponding key. It means that the key must be remembered always.
- In ArrayList, any number of null elements can be stored. While in HashMap, only one null key is allowed, but the values can be of any number.
ARRAYLIST | HASHMAP |
---|---|
The java ArrayList implements List Interface | The java HashMap is implements Map interface |
ArrayList always maintain insertion order of the elements | HashMap does not maintain the insertion order |
ArrayList only stores value or element | HashMap stores key and value pairs |
ArrayList can contain duplicate elements | HashMap does not contain duplicate keys but contain duplicate values. |
We can have any numbers of null elements in ArrayList | We can have only one null key and any number of null values in HashMap |
ArrayList get() method always gives an O(1) performance | HashMap get()method can be O(1) in the best case and O(n) in the worst case |
0 comments:
Post a Comment