Skip to content
Advertisement

How does get method works in hashmap if hashcode returns a contant value and equals return false?

I have Dept class as follows, i have overridden hashcode and equals method. Hashcode returns a constant value and equals return false always.

public class Dept {
    
        private int depid;
        private String deptname;
    
        public Dept(int depid, String deptname) {
            super();
            this.depid = depid;
            this.deptname = deptname;
        }
    
        public int getDepid() {
            return depid;
        }
    
        public void setDepid(int depid) {
            this.depid = depid;
        }
    
        public String getDeptname() {
            return deptname;
        }
    
        public void setDeptname(String deptname) {
            this.deptname = deptname;
        }
    
        @Override
        public int hashCode() {
    
            return 100;
        }
    
        @Override
        public boolean equals(Object obj) {
    
            return false;
        }
    
        @Override
        public String toString() {
            return "Dept [depid=" + depid + ", deptname=" + deptname + "]";
        }
    }

I have a main method

public static void main(String[] args) {
        Dept dept = new Dept(1, "it");
        Dept dept1 = new Dept(1, "it");
        Dept dept2 = new Dept(1, "it");

        HashMap<Dept, String> map = new HashMap<>();
        map.put(dept, "a");
        map.put(dept1, "b");
        map.put(dept2, "c");

        System.out.println(map.get(dept2));// returns c
        System.out.println(map.get(dept1));// returns b
}

According to the theory i have read, hashcode returning a constant value will give us the same index of bucket in hashmap hence values are stored in a single bucket For equals method, it is returning false and hence logically same dept object are saved multiple times. How is get method returning the exact correct value from hashmap?

Advertisement

Answer

Since an object is always supposed to be equals to itself, HashMap first checks using == (object identity), since this is much faster and will match in many common use cases.

Advertisement