简体   繁体   中英

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?

.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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM