Java 1.8 overridden equals() not called by Collection removeAll()
17:05 12 Apr 2017

In 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 because 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 classes = new HashSet<>();

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

}

public class Main (){

    private void method(MyClassContainer contClass) {
    
    if (true){
        Set temp = some valid Set;         
        temp.removeAll(contClass.getClasses());
    }

}

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

java java-8 overriding equals removeall