javaequalshashcodehashset

How hashset checks for duplicate elements?


Kindly look into my code :

HashSet<A> set = new HashSet<A>();
for (int i = 0; i < 10; i++)
    set.add(new A());
System.out.println(set.contains(new A()));

Class A is defined as :

class A {
    public boolean equals(Object o) {
        return true;
    }    
    public int hashCode() {
        return (int) (Math.random()%100);
    }
}

If hashset uses hashmap inside......why is the output true ? Because different hashcodes means their bucket location is different . So how checking for new A() returns true .

Also if I return 1 always from hashcode output is true which seems ok.


Solution

  • The reason is your hashcode function:

    (int) (Math.random()%100);
    

    always returns 0. So all A elements always have the same hashcode. Therefore all A elements will be in the same bucket in the HashSet so since your equals will always return true. As soon as it finds an A in the same bucket (in this case always) it will return true that that A is alreay contained.

    Math.random() returns a number between 0 and 1 so that modulo anything will always be0.

    you probably meant do to * instead of % to get random numbers between 0 and 100

     (int) (Math.random() * 100);
    

    Does what you want