Use Custome class as key in map

If we wish to create a HashMap of our own class, we need to ensure that the state change for the key object does not change the hash code of the object. One of the ways of doing this is by making key objects IMMUTABLE. This can be done by overriding the hashCode() method.

Approach

Example:

Input:  null->null->Add first -> add Second-> add first again
Note: We are adding same object twice to check key is working or not
null null
Student [name=Shyam, rollNo=1002] Shyam
Student [name=Ram, rollNo=1001] Ram


Java


import java.util.HashMap;

public class HashMapKey {
    public static void main(String[] args) {
        HashMap<StudentStringsMap = new HashMap<>();
        // null checking
        sMap.put(nullnull);
        sMap.put(nullnull);
        // First object
        Student s1 = new Student();
        s1.setName("Ram");
        s1.setRollNo("1001");
        sMap.put(s1, s1.getName());
        // Second different object
        Student s2 = new Student();
        s2.setName("Shyam");
        s2.setRollNo("1002");
        sMap.put(s2, s2.getName());

        // Third same object to s1
        Student s3 = new Student();
        s3.setName("Ram");
        s3.setRollNo("1001");
        sMap.put(s3, s3.getName());

        sMap.forEach((K, V) -> System.out.println(K + " " + V));
    }

    static class Student {
        String name;
        String rollNo;

        public Student() {
            super();
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getRollNo() {
            return rollNo;
        }

        public void setRollNo(String rollNo) {
            this.rollNo = rollNo;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((name == null? 0 : name.hashCode());
            result = prime * result + ((rollNo == null? 0 : rollNo.hashCode());
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Student other = (Student) obj;
            if (name == null) {
                if (other.name != null)
                    return false;
            } else if (!name.equals(other.name))
                return false;
            if (rollNo == null) {
                if (other.rollNo != null)
                    return false;
            } else if (!rollNo.equals(other.rollNo))
                return false;
            return true;
        }

        @Override
        public String toString() {
            return "Student [name=" + name + ", rollNo=" + rollNo + "]";
        }

    }
}

No comments:

Post a Comment