Containing equal objects in a HashSet

Hello I found such a collection related question.

public class Person {
    private String name;

    public Person(String name){
        this.name=name;
    }

    public boolean equals(Object o){
        if(!(o instanceof Person))return false;
        Person p=(Person)o;
        return p.name.equals(this.name);
    }

    public static void main(String[] args) {
        HashSet<Person> hs=new HashSet<Person>();
        hs.add(new Person("Hi"));
        hs.add(new Person("Hi"));
        hs.add(new Person("Hi"));
        hs.add(new Person("Hi"));

        System.out.println("Elements"+hs.size());
    }
}

      

The Hashset size is set to 4. But shouldn't it be 1? Since the equals method is implemented, can a HashSet contain multiple Person objects with the same name?

Do all Person objects have the same hashcode since the hashCode method is not overridden?

+3


source to share


1 answer


.equals()

not enough. You need .hashCode()

.

When you implement it, as a rule of thumb, always implement something else!

And obey the contract; in particular, two instances of the same class that .equals()

must have the same .hashCode()

.




Now, "24", as its name suggests, depends on ... Hashes. And in this case, by the result .hashCode()

. Depending on the result, it will insert the object you are adding into another hash store.

And since your objects have different hashes, they end up in four different buckets ...

+5


source







All Articles