Differences between HashMap and LinkedHashMap in Java

When you need to store and retrieve data using key-value pairs in Java, you have several options. Two popular classes for this purpose are HashMap and LinkedHashMap. In this article, we'll discuss the similarities and differences between these two classes and provide examples to help you understand them better.

Both HashMap and LinkedHashMap implement the Map interface in Java. This means they both store unique keys with corresponding values. You can use these keys to quickly retrieve their corresponding values. Additionally, both classes allow you to iterate through the keys.

Differences between HashMap and LinkedHashMap in Java

The primary difference between the two classes is the ordering of the keys. HashMap does not guarantee any specific order for the keys when iterating through them. This is because it is implemented as an array of linked lists. LinkedHashMap, on the other hand, guarantees the order of keys based on the order in which they were inserted. It is implemented as a doubly-linked bucket.

To better understand this, let's take a look at an example:

Suppose you have a list of numbers: 1, -1, 0, 2, -2. You want to store these numbers as keys with their corresponding absolute values as values in a HashMap and a LinkedHashMap. Here's how you would do it:

sql
HashMap<Integer, Integer> hashMap = new HashMap<>(); LinkedHashMap<Integer, Integer> linkedHashMap = new LinkedHashMap<>(); int[] numbers = {1, -1, 0, 2, -2}; for (int number : numbers) { int absoluteValue = Math.abs(number); hashMap.put(number, absoluteValue); linkedHashMap.put(number, absoluteValue); }

Now let's say you want to iterate through the keys and print them out in the order they were inserted. Here's how you would do it:

vbnet
System.out.println("HashMap:"); for (Integer key : hashMap.keySet()) { System.out.println(key); } System.out.println("LinkedHashMap:"); for (Integer key : linkedHashMap.keySet()) { System.out.println(key); }

The output for the HashMap will be in arbitrary order, while the output for the LinkedHashMap will be in the order they were inserted:

diff
HashMap: 0 1 2 -1 -2 LinkedHashMap: 1 -1 0 2 -2

Another difference between HashMap and LinkedHashMap is their time guarantees for lookup and insertion. Both classes offer O(1) time complexity for lookup and insertion. However, LinkedHashMap is slightly slower than HashMap due to the added overhead of maintaining the order of keys.

In real-life applications, TreeMap is another class that can be useful for ordering keys alphabetically. However, it is slower than both HashMap and LinkedHashMap.

In summary, both HashMap and LinkedHashMap offer key-value mapping with fast lookup and insertion. The main difference between them is the order of keys. If order doesn't matter, use HashMap for its speed and low overhead. If order matters, use LinkedHashMap to maintain the order of insertion.

Previous Post Next Post