Sitemap
Mayanknegi

Mayanknegi

I am a software developer

What is linkedHashMap in Java?

2 min readSep 28, 2024

--

The LinkedHashMap class is a hash table and linked list implementation of the Map interface, which provides a way to store and retrieve elements in a key-value pair format. It is similar to the HashMap class but has an additional feature: it maintains a doubly linked list running through all its entries. This allows for efficient iteration over the map in the order in which keys were inserted.

Here are some key features of the LinkedHashMap class:

Key Features:

  1. Ordered iteration: The LinkedHashMap class maintains a doubly-linked list of its entries, which allows for efficient iteration over the map in the order in which keys were inserted.
  2. Hash table implementation: Like HashMap, LinkedHashMap uses a hash table to store its elements, which provides fast lookup, insertion, and deletion operations.
  3. Fail-fast iterators: The iterators returned by the iterator() method are fail-fast, meaning that they will throw a ConcurrentModificationException if the map is modified structurally while iterating over it.
  4. Null keys and values allowed: Unlike some other map implementations, LinkedHashMap allows null keys and values.

Constructors:

The LinkedHashMap class has several constructors:

  1. LinkedHashSet(): Creates an empty linked hash set with default initial capacity (16) and load factor (0.75).
  2. LinkedHashSet(int initialCapacity): Creates an empty linked hash set with specified initial capacity and default load factor (0.75).
  3. LinkedHashSet(int initialCapacity, float load factor): Creates an empty linked hash set with specified initial capacity and load factor.
  4. LinkedHashSet(Map<? extends K, ? extends V> m): Creates a new linked hash set with elements from the specified map.

Methods:

Some commonly used methods of the LinkedHashMap class include:

  1. put(K key, V value): Inserts or updates an entry in the map.
  2. get(Object key): Retrieves the value associated with the specified key.
  3. containsKey(Object key): Returns true if the map contains an entry with the specified key.
  4. remove(Object key): Removes an entry from the map based on its key.
  5. clear(): Removes all entries from the map.

Use cases:

Get Mayanknegi’s stories in your inbox

Join Medium for free to get updates from this writer.

The LinkedHashMap class is beneficial when you need to maintain a cache or a configuration file where you want to preserve the insertion order.

--

--