Ask a Question
Advertise on boostr.in
Difference between ArrayList and HashMap in Java
ArrayList and HashMap are two commonly used collection classes in Java. Even though both are the part of collection framework, the way they store and process the data is entirely different. In this post we will see the main differences between these two collections.
ArrayList vs HashMap in Java
1) Implementation: ArrayList implements List Interface while HashMap is an implementation of Map interface. List and Map are two entirely different collection interfaces.
2) Memory consumption: ArrayList stores the elementâ€™s value alone and internally maintains the indexes for each element.
arraylist = new ArrayList
//String value is stored in array list
Â arraylist.add("Test String");
HashMap stores key & value pair. For each value there must be a key associated in HashMap. That clearly shows that memory consumption is high in HashMap compared to the ArrayList.
hmap= new HashMap
//String value stored along with the key value in hash map
Â hmap.put(123, "Test String");
3) Order: ArrayList maintains the insertion order while HashMap doesnâ€™t. Which means ArrayList returns the list items in the same order in which they got inserted into the list. On the other side HashMap doesnâ€™t maintain any order, the returned key-values pairs are not sorted in any kind of order.
4) Duplicates: ArrayList allows duplicate elements but HashMap doesnâ€™t allow duplicate keys (It does allow duplicate values).
5) Nulls: ArrayList can have any number of null elements. HashMap allows one null key and any number of null values.
6) get method: In ArrayList we can get the element by specifying the index of it. In HashMap the elements is being fetched by specifying the corresponding key.
Jun 11, 2015
Java Interview Questions
to add a comment.
Your name to display (optional):
Email me at this address if my answer is selected or commented on:
Email me if my answer is selected or commented on
Privacy: Your email address will only be used for sending these notifications.
To avoid this verification in future, please