Back to photostream

LinkedHashMap in Java

LinkedHashMap class in Java is a LinkedList implementation that is similar to a HashMap but preserves the insertion order. It extends the HashMap class and implements the Map interface. It uses the doubly LinkedList implementation to iterate through all the nodes in the LinkedHashMap.

Features of LinkedHashMap

 

- It maintains the order of the entries in the same way it inserts the elements.

- LinkedHashMap can contain only unique data

- Can have only one null key but multiple null values.

 

Constructors in LinkedHashMap

Below are the constructors present in the LinkedHashMap class.

 

Methods of LinkedHashMap in Java

 

Working of LinkedHashMap in Java

LinkedHashMap in Java works on the implementation of the doubly linked list which means it contains addresses of the next element and the previous element. In this way, it also maintains the insertion order.

 

In the below diagram, prev denotes the address of the previous element and next denotes the address of the next element.

 

Example: Adding elements to the LinkedHashMap

Below is an example of adding elements to the LinkedHashMap. We can see that it maintains the insertion order and displays the elements in the same order as we have inserted it. But this functionality is not present in the HashMap which is the major difference.

import java.util.LinkedHashMap;

 

public class AddElements {

 

public static void main(String args) {

LinkedHashMap lh = new LinkedHashMap();

lh.put(1, "Aarthi");

lh.put(2,

 

www.tutorialcup.com/java/linkedhashmap-in-java.htm

24 views
0 faves
0 comments
Uploaded on October 9, 2021