Search code examples
collectionsjava-8overridingequalsremoveall

Java 1.8 overridden equals() not called by Collection removeAll()


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


Solution

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

    @Override
    public int hashCode() {
        return Objects.hash(getConnectionID());
    }