user2445123
user2445123

Reputation:

Containing equal objects in the HashSet

Hello I found a question like this related to collections.

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 size of the Hashset is given as 4. But doesn't it need to be 1? Since the equals method has implemented, can the HashSet contain multiple Person objects with the same name?

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

Upvotes: 3

Views: 235

Answers (1)

fge
fge

Reputation: 121840

.equals() is not enough. You need .hashCode().

When you implement one, as a rule of thumb, always implement the other!

And obey the contract; in particular, two instances of a same class which are .equals() must have the same .hashCode().


Now, a HashSet, as its name implies, relies on... Hashes. And in this case, on the result of .hashCode(). Depending on the result, it will insert the object you add into a different hash bucket.

And as your objects all have different hash codes, they end up in four different buckets...

Upvotes: 5

Related Questions