Skip to main content

How to add objects in a HashMap

Points To Remember
  • HashMap saves objects in form of key-value pair in form of Entry object (Map.Entry).
  • We can use any object as a key on which hashCode() and equals() can be applied.
  • We cannot use primitive datatypes as keys or values.
  • We can have only one value corresponding to a key, other values will get overridden.
  • A hashMap can contain a single null key.
  • Initial size of a HashMap is 16 and its load factor is 0.75 after this HashMap gets rehashed.
Program : Adding Objects to HashMap
Below program shows how to save key-value pairs as entry objects in a HashMap. We use put() method to store key-value pairs in a Hashmap.
import java.util.HashMap;

class Test{

public static void main(String args[]){

// Declaring and Initializing a HashMap
HashMap<String, String> map = new HashMap<String, String>();

// Adding Objects TO HashMap
map.put("key 1","value 1");
map.put("key 2","value 2");
map.put("key 3","value 3");
map.put("key 4","value 4");
map.put("key 5","value 5");
}

}

Comments