LinkedHashMap in Java is a class in collections framework .LinkedHashMap implements Map interface.It is a linked list version of HashMap. As you know, a HashMap is unsorted and unordered collection.If we need to get the order of iteration same as that of order of insertion , then LinkedHashMap can be used.
Let us see an example.From the output we can understand that the order of insertion is preserved.
import java.util.*; public class LinkedHashMapSample { Map map = null; public LinkedHashMapSample() { } public void addItemsToMap() { System.out.println("Adding contents to map "); map = new LinkedHashMap(); String[] listItems = {"dog", "cat", "cow", "elephant", "sheep"}; for (int i = 0; i < listItems.length; i++) { map.put("Item"+i, listItems[i]); } } public void displayMap() { System.out.println("Displaying contents of map"); Set set = map.entrySet(); System.out.println("Size = " + set.size()); Iterator i = set.iterator(); while (i.hasNext()) { Map.Entry entry = (Map.Entry) i.next(); System.out.print(entry.getKey() + ": "); System.out.println(entry.getValue()); } } public void removeItems() { map.clear(); System.out.println("Displaying contents after removal:"); displayMap(); } public static void main(String[] args) { LinkedHashMapSample sample = new LinkedHashMapSample(); sample.addItemsToMap(); sample.displayMap(); sample.removeItems(); } }
Now let us see the output.
Output
Adding contents to map
Displaying contents of map
Size = 5
Item0: dog
Item1: cat
Item2: cow
Item3: elephant
Item4: sheep
Displaying contents after removal:
Displaying contents of map
Size = 0
So the order of insertion is preserved.
LinkedHashMap and hashCode() method
LinkedHashMap is relying on hash code values of key objects.If we use objects of our own classes as keys in LinkedHashMap , then we need to override the hashCode() and equals() methods of java.lang.Object class in our class.The hashCode() method should return same hash code for meaningfully equal objects. If we are not overriding the hashCode() ,objects with exactly same contents (meaningfullly same objects) can occur multiple times in our data structure.This is duplication .Also search for a particular object also return false outcome.This is well explained here with examples.
We are storing Student object vs String data in our LinkedHashMap. Student object is the key for a particular String data.
case 1.Without overriding hashCode() and equals()
See the Student.java first.We are not overriding the hashCode() and equals() values.
public class Student { private int rollNumber; private String name; public Student(int number, String name) { this.rollNumber = number; this.name = name; } public int getRollNumber() { return rollNumber; } public void setRollNumber(int rollNumber) { this.rollNumber = rollNumber; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String toString(){ return "Roll Number : "+getRollNumber() +" ; Name : "+getName(); } }
Now let us see our Main.java.
import java.util.LinkedHashMap; import java.util.Map; public class Main { private Map<Student, String> map = null; public Main() { map = new LinkedHashMap<Student, String>(); } public void addItems() { Student student1 = new Student(1, "Bijoy"); Student student2 = new Student(2, "Dexter"); Student student3 = new Student(1, "Bijoy"); map.put(student1,"First"); map.put(student2,"Second"); map.put(student3,"Third"); System.out.println("Size of Map = "+map.size()); } public void display() { Student student = new Student(1,"Bijoy"); System.out.println("Is present or not ? "+map.containsKey(student)); } public static void main(String[] args) { Main main = new Main(); main.addItems(); main.display(); } }
In the addItems() method. We are initializing few Student objects . And String data is storing against these Student keys.The objects student1 and student3 are meaningfully same .But both are having different hash code values since we have not overridden the hashCode() method in Employee.java.So meaningfully same objects will be duplicated in our LinkedHashMap.So displaying the size makes our understanding clear.Here student1 and student3 are treating as different objects though they are meaningfully same . So size will be 3.
And in the display() method we are creating an object student.Its attribute values are exactly same as that of student1 and student3 (we inserted those two objects in addItems() method).But student , stdent1 and student3 are having different hashCodes() here .So false will be displayed.(For more details about hashCode () implementation see my article)
Output
Size of Map = 3
Is present or not ? false
Case 2 .By overriding hashCode() and equals()
Now modify our Student.java by overriding hashCode() and equals().So the modified Student.java becomes:
public class Student { private int rollNumber; private String name; public Student(int number, String name) { this.rollNumber = number; this.name = name; } public int getRollNumber() { return rollNumber; } public void setRollNumber(int rollNumber) { this.rollNumber = rollNumber; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String toString(){ return "Roll Number : "+getRollNumber() +" ; Name : "+getName(); } public int hashCode(){ return 10; } public boolean equals(Object object){ Student student = (Student)object; boolean status = false; if(getRollNumber() == student.getRollNumber() && getName().equalsIgnoreCase(student.getName())){ status = true; } else{ status = false; } return status; } }
Here we are getting same hash code values for all objects. That means all objects are storing in same memory slot.
Use the previos Main.java here also . The student1and student3 are having same hash code values. And the equals() method gives the output in such a way that both are equal.So in addItems() , emp3 is not taking as a key.Only student1 and student2 as taking as keys.And also in display() method student object is having the same hash code value of student1 in addItems() method.student1 is already there in our map as key.So search for student gives true.
Let us verify the output
Output
Size of Map = 2
Is present or not ? true