Reputation: 21480
In Java, ArrayList
and HashMap
are used as collections. But I couldn't understand in which situations we should use ArrayList
and which times to use HashMap
. What is the major difference between both of them?
Upvotes: 45
Views: 70661
Reputation: 2322
We should consider below point before using ArrayList
and HashMap
.
ArrayList
ArrayList
implements List
InterfaceArrayList
always maintain the insertion order of the elementsArrayList
only stores value or elementArrayList
can contain duplicate elementsArrayList
ArrayList
get()
method always gives an O(1)
performanceHashMap
HashMap
implements Map
interfaceHashMap
does not maintain the insertion order.HashMap
stores key and value pairsHashMap
does not contain duplicate keys but contains duplicate values.HashMap
HashMap
get()
method can be O(1)
in the best case and O(n)
in the worst caseExample:
// Importing all utility classes
import java.util.*;
// Main class
class Demo {
public static void main(String args[]) {
// Creating ArrayList of string type
ArrayList<String> list = new ArrayList<String>();
// Adding values in ArrayList using standard add() method
list.add("A");
list.add(null); // Adding first null value
list.add("C");
list.add(null); // Adding second null value
list.add(null); // Adding third null value
// Printing ArrayList object
System.out.println("ArrayList: " + list);
//Creating HashMap object of integer and string type
HashMap<Integer, String> hm = new HashMap<Integer, String>();
// Adding value in HashMap using standard put method
hm.put(1, "A");
hm.put(2, "B");
hm.put(null, "C"); // Adding first null key
hm.put(null, null); // Again adding null key which replace value of first insert null key value
hm.put(3, null); // Adding second null value with different key
// Printing the elements of Hashmap
System.out.println("HashMap: " + hm);
}
}
Output
ArrayList: [A, null, C, null, null]
HashMap: {null=null, 1=A, 2=B, 3=null}
In above output we can see ArrayList
contains duplicate null
values and Hashmap
contains duplicate null
value but key is not duplicate.
HashMap
replace new value when we add value with some existing key.
Reference : https://www.geeksforgeeks.org/difference-between-arraylist-and-hashmap-in-java/
Upvotes: 0
Reputation: 68847
If you use an ArrayList
, you have to access the elements with an index (int
type). With a HashMap
, you can access them by an index of another type (for example, a String
)
HashMap<String, Book> books = new HashMap<String, Book>();
// String is the type of the index (the key)
// and Book is the type of the elements (the values)
// Like with an arraylist: ArrayList<Book> books = ...;
// Now you have to store the elements with a string key:
books.put("Harry Potter III", new Book("JK Rownling", 456, "Harry Potter"));
// Now you can access the elements by using a String index
Book book = books.get("Harry Potter III");
This is impossible (or much more difficult) with an ArrayList
. The only good way to access elements in an ArrayList
is by getting the elements by their index-number.
So, this means that with a HashMap
you can use every type of key you want.
Another helpful example is in a game: you have a set of images, and you want to flip them. So, you write a image-flip method, and then store the flipped results:
HashMap<BufferedImage, BufferedImage> flipped = new HashMap<BufferedImage, BufferedImage>();
BufferedImage player = ...; // On this image the player walks to the left.
BufferedImage flippedPlayer = flip(player); // On this image the player walks to the right.
flipped.put(player, flippedPlayer);
// Now you can access the flipped instance by doing this:
flipped.get(player);
You flipped player once, and then store it. You can access a BufferedImage
with a BufferedImage
as key-type for the HashMap
.
I hope you understand my second example.
Upvotes: 17
Reputation: 17601
Not really a Java specific question. It seems you need a "primer" on data structures. Try googling "What data structure should you use"
Try this link http://www.devx.com/tips/Tip/14639
From the link :
Following are some tips for matching the most commonly used data structures with particular needs.
A hashtable, or similar data structures, are good candidates if the stored data is to be accessed in the form of key-value pairs. For instance, if you were fetching the name of an employee, the result can be returned in the form of a hashtable as a (name, value) pair. However, if you were to return names of multiple employees, returning a hashtable directly would not be a good idea. Remember that the keys have to be unique or your previous value(s) will get overwritten.
This is a good option when you desire sequential or even random access. Also, if data size is unknown initially, and/or is going to grow dynamically, it would be appropriate to use a List or Vector. For instance, to store the results of a JDBC ResultSet, you can use the java.util.LinkedList. Whereas, if you are looking for a resizable array, use the java.util.ArrayList class.
Never underestimate arrays. Most of the time, when we have to use a list of objects, we tend to think about using vectors or lists. However, if the size of collection is already known and is not going to change, an array can be considered as the potential data structure. It's faster to access elements of an array than a vector or a list. That's obvious, because all you need is an index. There's no overhead of an additional get method call.
4.Combinations
Sometimes, it may be best to use a combination of the above approaches. For example, you could use a list of hashtables to suit a particular need.
And from JDK 1.2 onwards, you also have set classes like java.util.TreeSet, which is useful for sorted sets that do not have duplicates. One of the best things about these classes is they all abide by certain interface so that you don't really have to worry about the specifics. For e.g., take a look at the following code.
// ...
List list = new ArrayList();
list.add(
Upvotes: 14
Reputation: 61
A Map vs a List.
In a Map, you have key/value pairs. To access a value you need to know the key. There is a relationship that exists between the key and the value that persists and is not arbitrary. They are related somehow. Example: A persons DNA is unique (the key) and a persons name (the value) or a persons SSN (the key) and a persons name (the value) there is a strong relationship.
In a List, all you have are values (a persons name), and to access it you need to know its position in the list (index) to access it. But there is no permanent relationship between the position of the value in the list and its index, it is arbitrary.
Upvotes: 4
Reputation: 10151
You are asking specifically about ArrayList and HashMap, but I think to fully understand what is going on you have to understand the Collections framework. So an ArrayList implements the List interface and a HashMap implements the Map interface. So the real question is when do you want to use a List and when do you want to use a Map. This is where the Java API documentation helps a lot.
List:
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.
Map:
An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
So as other answers have discussed, the list interface (ArrayList) is an ordered collection of objects that you access using an index, much like an array (well in the case of ArrayList, as the name suggests, it is just an array in the background, but a lot of the details of dealing with the array are handled for you). You would use an ArrayList when you want to keep things in sorted order (the order they are added, or indeed the position within the list that you specify when you add the object).
A Map on the other hand takes one object and uses that as a key (index) to another object (the value). So lets say you have objects which have unique IDs, and you know you are going to want to access these objects by ID at some point, the Map will make this very easy on you (and quicker/more efficient). The HashMap implementation uses the hash value of the key object to locate where it is stored, so there is no guarentee of the order of the values anymore. There are however other classes in the Java API that can provide this, e.g. LinkedHashMap, which as well as using a hash table to store the key/value pairs, also maintains a List (LinkedList) of the keys in the order they were added, so you can always access the items again in the order they were added (if needed).
Upvotes: 82
Reputation: 1499770
Use a list for an ordered collection of just values. For example, you might have a list of files to process.
Use a map for a (usually unordered) mapping from key to value. For example, you might have a map from a user ID to the details of that user, so you can efficiently find the details given just the ID. (You could implement the Map
interface by just storing a list of keys and a list of values, but generally there'll be a more efficient implementation - HashMap
uses a hash table internally to get amortised O(1) key lookup, for example.)
Upvotes: 4