Loading

HashMap

Key points:

  • HashMap is an implementation class of Map Interface.
  • It implements two Marker interfaces 1)Serializable and  2)Cloneable.
  • The underlined data structure of HashMap is HashTable. 
  • Default capacity f hahmaps16 and it grows based on the load factor or fill ratio.
  • It doesn't follow the order of insertion.
  • The HashMap grows at runtime once the fill ratio or load factor is met the default load factor is 0.75.

Example:

package com.quipoin;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class Employee {
	public static void main(String[] args) {
		HashMap<Integer, String> hm=new HashMap<>();

		hm.put(101, "Ramesh");
		hm.put(105, "Anand");
		hm.put(104, "Pratap");
		hm.put(102, "Devaraj");
		hm.put(103, "Akhil");

		System.out.println("Employee list!!");
		System.out.println("--------------- ");
		System.out.println("Id\tName");
		System.out.println("--------------- ");
		Set<Integer> set=hm.keySet();
		Iterator<Integer> it=set.iterator();

		while(it.hasNext()){
			Integer key=it.next();
			String value=hm.get(key);
			System.out.println(key+"\t"+value);
		}
	}
}

Output:

Employee list!!
--------------- 
Id	    Name
--------------- 
101	    Ramesh
102	    Devaraj
103	    Akhil
104	    Pratap
105	    Anand

LinkedHashMap

Key Points:

  • LinkedHashMap is a subclass of HashMap.
  • The underlined data structure of LinkedHashMap is LinkedList and HashTable.
  • The difference between LinkedHashMap and HashMap is that HashMap doesn't maintain the order of insertion whereas LinkedHashMap maintains the order of insertion.

Example:

package com.quipoin;

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

public class Student {
	public static void main(String[] args) {
		LinkedHashMap<String, Integer> lhm=new LinkedHashMap<>();

		lhm.put("King", 121);
		lhm.put("John", 13);
		lhm.put("Akshay", 98);
		lhm.put("Raghav", 106);

		System.out.println(lhm);
		System.out.println("Student list!!");
		System.out.println("----------------");
		System.out.println("Name\tReg_No");
		System.out.println("----------------");
		Set<String> set=lhm.keySet();
		Iterator<String> it=set.iterator();
		while(it.hasNext()) {
			String key=it.next();
			Integer value=lhm.get(key);
			System.out.println(key+"\t"+value);
		}
	}
}

Output:

{King=121, John=13, Akshay=98, Raghav=106}
Student list!!
----------------
Name	Reg_No
----------------
King	121
John	13
Akshay	98
Raghav	106

Order of insertion is the main difference between HashMap and LinkedHashMap.