How to create a Java HashMap of user defined class type?

Pre-requisite: Internal working of HashMap, HashMap
If we wish to create a HashMap of our own class, we need to ensure that the hashcode() of the key of HashMap doesn’t change as if it happens then it is impossible to get object value of the key from HashMap.

On runtime, JVM processes hash code for each object and give it on interest. When we alter an objects’ state, JVM calculates its hash code again which may result in memory leak. To make things work what we have to do is make sure that state change for a key object does not change the hash code of object i.e. the key must have properly overridden equals() and hashcode() methods for it to work correctly.

One of the ways of doing this is by making key objects IMMUTABLE. Immutability allows you to get same hashcode every time, for a key object. This is the primary motivation behind why Immutable classes like String, Integer or other wrapper classes are a decent key object applicant. Learn more about this here- How to make class Immutable?

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java example to create a Java HashMap
// of user-defined class type
  
import java.util.*;
import java.io.*;
  
// User defined class
public class CustomKeyObject {
  
    public static class Student {
  
        private int rollno;
        private String name;
  
        // Constructor
        public Student(int rollno, String name)
        {
            this.rollno = rollno;
            this.name = name;
        }
  
        public String getname()
        {
            return this.name;
        }
  
        public int getmarks()
        {
            return this.rollno;
        }
  
        public void setname(String name)
        {
            this.name = name;
        }
  
        public void setmarks(int rollno)
        {
            this.rollno = rollno;
        }
  
        // Overriding the hashcode() function
        @Override
        public int hashCode()
        {
  
            // uses roll no to verify the uniqueness
            // of the object of Student class
  
            final int temp = 14;
            int ans = 1;
            ans = temp * ans + rollno;
            return ans;
        }
  
        // Equal objects must produce the same
        // hash code as long as they are equal
        @Override
        public boolean equals(Object o)
        {
            if (this == o) {
                return true;
            }
            if (o == null) {
                return false;
            }
            if (this.getClass() != o.getClass()) {
                return false;
            }
            Student other = (Student)o;
            if (this.rollno != other.rollno) {
                return false;
            }
            return true;
        }
    }
  
    // main method
    public static void main(String[] args)
        throws NumberFormatException,
               IOException
    {
        HashMap<Student, String> map = new HashMap<>();
  
        Student one = new Student(1, "Geeks1"); // key1
  
        Student two = new Student(2, "Geeks2"); // key2
  
        // put keys in map
        map.put(one, one.getname());
        map.put(two, two.getname());
  
        // changing key state so that
        // hashcode() should be calculated again
        one.setname("Not Geeks1");
        two.setname("Not Geeks2");
  
        // still prints Geeks1
        System.out.println(map.get(one));
  
        // still prints Geeks1
        System.out.println(map.get(two));
  
        // try with newly created key with same Rollno
        Student three = new Student(1, "Geeks3");
  
        // we get Geeks1
        System.out.println(map.get(three));
    }
  
    // This code is contributed by Subhesh
}

chevron_right


Output:

Geeks1
Geeks2
Geeks1


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


3


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.