Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement equals with Set

Tags:

java

equals

I have this class:

private static class ClassA{
int id;
String name;

public ClassA(int id, String name){
    this.id= id;
    this.name = name;
}

@Override
public boolean equals(Object o) {
    return ((ClassA)o).name.equals(this.name);
}   

}

Why this main is printing 2 elements if I am overwriting the method equals in ClassA to compare only the name?

public static void main(String[] args){
    ClassA myObject = new ClassA(1, "testing 1 2 3");
    ClassA myObject2 = new ClassA(2, "testing 1 2 3");    

    Set<ClassA> set = new HashSet<ClassA>();
    set.add(myObject);
    set.add(myObject2);   
    System.out.println(set.size()); //will print 2, but I want to be 1!
}

If I look into the Set Java documentation:

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

So apparently I only have to override equals, however I heard that I have also to override the hashcode, but why?

like image 291
Dayerman Avatar asked Aug 01 '26 08:08

Dayerman


1 Answers

They have different hashes because you didn't override hashCode. This means they were put in two different buckets in the HashSet, so they never got compared with equals in the first place.

I would add

public int hashCode() {
    return name.hashCode();
}

Notice id isn't used in the hashCode because it isn't used in equals either.

(P.S. I'd also like to point out the irony of having an id that isn't used in equals. That's just funny. Usually it's the other way around: the id is the only thing in equals!)

like image 160
corsiKa Avatar answered Aug 03 '26 23:08

corsiKa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!