0

on my IDE (eclipse neon) i m running jre 1.8. As you can see in the snippet code below i developed My Custom class overriding the equals method. That s cause i want to use my overridden version when i execute the removeAll method from a Set of my custom class.

Looking inside the jdk source code it's possible to verify that removeAll method uses the contains method which in turn uses the equals method of the Object class.

public class MyClass {
    private String connectionID;


    public MyClass (){      
    ...
    }


    @Override
    public boolean equals(Object obj) {      
        if (obj instanceof MyClass ){
            if (((MyClass )obj).getConnectionID().equalsIgnoreCase(this.getConnectionID())){
                return true;
            }
        }
        return false;
    }
...
}



public class MyClassContainer{

    private Set<MyClass> classes = new HashSet<>();

    public Set<MyClass> getClasses () {
        return this.classes ;
    }

}

public class Main (){

    private void method(MyClassContainer contClass) {

    if (true){
        Set<MyClass> temp = some valid Set;         
        temp.removeAll(contClass.getClasses());
    }

}

Launching this code i m realizing that the overridden equals method is never called.

What is it wrong?

Thanks

Alex
  • 1,515
  • 2
  • 22
  • 44
  • 1
    What kind of set implementation are you using ? Note that if you override equals, you should override hashCode as well to be consistent. This is probably your problem. – Alexis C. Apr 12 '17 at 20:52
  • 1
    Possible duplicate of [Why do I need to override the equals and hashCode methods in Java?](http://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java) – Joe C Apr 12 '17 at 21:11

1 Answers1

1

For it to work correctly, you need to override hashCode as well:

@Override
public int hashCode() {
    return Objects.hash(getConnectionID());
}
Jacob G.
  • 28,856
  • 5
  • 62
  • 116
  • *Beware!* if your equality is implemented using `equalsIgnoreCase`, the hash code must be case insensitive as well, which this implementation doesn’t offer. Though, in this case, it’s very likely that the ID comparison isn’t actually supposed to be case insensitive. So the implementation of `equals` can be corrected and simplified to `return (obj instanceof MyClass) && ((MyClass)obj).getConnectionID().equals( this.getConnectionID()));`… – Holger Apr 13 '17 at 12:23