Question

I am trying to understand TreeSet. I have created am Employee object and trying to add the employee object to TreeSet. to realize this I have created class called sortName, which sorts the employee objects based on name. and I have written an equals method too (just to understand the execution flow). I read that in TreeSet to add elements in some sorted we must implement comparator interface and overwrite two methods (compare and equals) ofcourse equals is optional. When i try to run the program it works, I observed that the equals method is never invoked, why is that?

Lets draw a comparison between HashSet and TreeSet. in HashSet when the hashCode is same then it checks for equals method, otherwise not. I am interested in knowing how is the working in TreeSet? Can anyone give me a example where even equals method is invoked for TreeSet?

public int compare(Object Obj1, Object Obj2) {
    System.out.println("compare");
    if (Obj1 instanceof Employee19 && Obj2 instanceof Employee19) {
        Employee19 emp1=(Employee19) Obj1;
        Employee19 emp2=(Employee19) Obj2;

        return emp1.sname.compareTo(emp2.sname);
    }
    return 0;
}

public boolean equals(Object obj){
    System.out.println("equals");
    return true;
}

I even checked this link but that was not what I was looking... HashSet with two equals object?

Was it helpful?

Solution

The TreeSet doesn't need to use the equals method, because it gets all the information it needs from the Comparator's compare method (or the compareTo method if it is relying on its elements being Comparable). Either way can tell if elements are equivalent, if the appropriate method returns 0.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top