avatarVikram Gupta

Summary

The webpage provides a comprehensive guide on the LinkedHashMap class in Java, detailing its definition, usage, internal workings, and comparison with other collection classes.

Abstract

The article on the LinkedHashMap class in Java serves as an in-depth resource for developers seeking to understand this map implementation. It explains that LinkedHashMap extends HashMap and maintains a doubly-linked list to ensure predictable iteration order, which is typically the order in which keys are inserted. The guide also covers the internal mechanisms, such as the use of a doubly-linked list with 'before' and 'after' pointers, and how LinkedHashMap can switch to a tree structure under certain conditions. The article emphasizes the practical applications of LinkedHashMap, such as creating a map copy with the same order as the original or implementing an LRU cache based on access order. It concludes by suggesting further reading on related Java collection classes.

Opinions

  • The author posits that learning about collection classes like LinkedHashMap is crucial for real-world application development.
  • LinkedHashMap is presented as a superior alternative to HashMap when predictable iteration order is required, without the overhead of TreeMap.
  • The article suggests that maintaining insertion order is a key feature of LinkedHashMap, which is not affected by key re-insertion.
  • The author implies that understanding the internal workings of LinkedHashMap, including its transformation into a tree under specific conditions, is important for developers to fully leverage its capabilities.
  • The guide encourages the use of LinkedHashMap for creating ordered copies of maps and for building LRU caches, highlighting its versatility.
  • By providing a list of related articles, the author indicates the importance of a comprehensive understanding of various Java collection classes for interview preparation and general proficiency in Java programming.

Java Collection Interview Questions

Complete Guide on LinkedHashMap in Java

Everything you need to know about LinkedHashMap in Java.

The red-black tree that is internally used for TreeMap

Learning collection classes are essential as they are heavily used while creating the real-world Application. There are a few important collection classes that I have already covered (HashMap, ConcurrentHashMap, TreeMap). This article is a continuation of that and we’ll deep dive into what, why, and how of the LinkedHashMap class.

What Is LinkedHashMap?

  • LinkedHashMap is Hashtable and linked list implementation of the Map interface, with predictable iteration order.
  • This implementation differs from HashMap in that, it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys are inserted into the map (insertion order).
  • Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately before the invocation.)
  • This implementation spares its clients from the unspecified, generally chaotic ordering provided by HashMap (and Hashtable), without incurring the increased cost associated with TreeMap.
  • It can be used to produce a copy of a map that has the same order as the original, regardless of the original map’s implementation.

LinkedHashMap class that extends HashMap and implements Map.

public class LinkedHashMap<K,V>
    extends HashMap<K,V>
    implements Map<K,V>

LinkedHashMap is defined in java.util Package.

LinkedHashMap Example:

Let’s create a basic LinkedHashMap and add some items to it and see how it stores them.

package com.company;

import java.util.Iterator;
import java.util.LinkedHashMap;

public class Main {
    public static void main(String[] args) {
        LinkedHashMap<String, String> cityPoints = new LinkedHashMap<>();

        cityPoints.put("Pune", "Ganesh Temple");
        cityPoints.put("Mumbai", "Gateway Of India");
        cityPoints.put("Delhi", "Red fort");

        Iterator<String> cities = cityPoints.keySet().iterator();
        while (cities.hasNext()) {
            String city = cities.next();
            System.out.println("City name : " + city);
        }
    }
}

Output:

City name : Pune
City name : Mumbai
City name : Delhi

In this example, the output is printed in the order the items were inserted into the map.

Internal Working of LinkedHashMap:

Internally LinkedHashMap class uses a Doubly Linked list(hold on there is a catch 🤔). The below static inner class Entry is extending HashMap.Node class and has two extra pointers (before and after) along with all attributes of Nodeclass from HashMap class (attributes: hash, key, value, next). This entry is nothing but a node in a doubly-linked list and stores the key-value pairs with its before and after pointers.

    static class Entry<K,V> extends HashMap.Node<K,V> {
        Entry<K,V> before, after;
        Entry(int hash, K key, V value, Node<K,V> next) {
            super(hash, key, value, next);
        }
    }

Each node of DLL has two pointers (before and after) and this list also has a head pointer that points to the first node(eldest) of the list. Similarly, it also has a tail pointer that points to the last(youngest) node of the list.

transient LinkedHashMap.Entry<K,V> head;
transient LinkedHashMap.Entry<K,V> tail;

Node class that is being referred from the HapMap class:

    /**
     * Basic hash bin node, used for most entries.  (See below for
     * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
     */
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }

Now the Catch 😈:

LinkedHashMap works on the principle of hashing and linked lists. As you know in the case of HashMap that can get converted to a tree in special scenarios where all the entries are going into the same bucket and crossing the threshold value. Similarly, LinkedHashMap can also be converted to a tree when all the entries are going to the same bucket.

Note that insertion order is not affected if a key is re-inserted into the map.

Why Do We Need LinkedHashMap?

It can be used to produce a copy of a map that has the same order as the original, regardless of the original map’s implementation:

void foo(Map m) {
 Map copy = new LinkedHashMap(m);
 …
}
  • This technique is particularly useful if a module takes a map on input, copies it, and later returns results whose order is determined by that of the copy. (Clients generally appreciate having things returned in the same order they were presented.)
  • A special constructor is provided to create a linked hash map whose order of iteration is the order in which its entries were last accessed, from least-recently accessed to most-recently (access-order). This kind of map is well-suited to building LRU caches.

That’s all for this article. Hope you enjoyed it.

You Can Follow Vikram Gupta For Similar Content.

1. Comparing ArrayList and LinkedList in Java

2. Internal Working of HashMap in Java

3. Comparing HashMap and ConcurrentHashMap in Java

4. Complete the Guide on LinkedHashMap in Java

5. Internal Working Of TreeMap in Java Collection Framework

6. Internal Working of HashSet in Java

Linkedhashmap In Java
Linkedhashmap
Hashmap
Treemap
Collection In Java
Recommended from ReadMedium