I have a class A whose instances have 8 attributes, the last two are of the type "int". I have implemented the Comparator interface, where elements have to be compared according to the 7. attribute. If values of the 7. attribute are equal, object have to be compared additionally by the 8. attribute, which values cannot be equal. I have build a TreeSet with this comparator in constructor in some another class. Operating with this TreeSet I meet unexpected behaviour.
compare() is implemented as follows:
// class AComparator
public int compare(A a1, A a2) {
int result = a1.get7attriibute() - a2.get7attribute();
if (result == 0) {
return a1.get8attribute() - a2.get8attribute();
} else {
return result;
}
}
TreeSet is initialized as follows:
TreeSet<A> ts = new TreeSet<A>(new AComparator());
Later in the code I use the following BiFunction:
BiFunction<A,A,A> funName = (v,u) -> {
return v.get8attribute() > u.get8Attribute() ? v : u;
}
Function usage is as follows:
A result = funName.apply(a1,a2); // where a1 and a2 from the TreeSet
Using
ts.remove(result);
later in the code I expect the program to delete the result from the TreeSet. However, in debugger I see that result have a different ID from a1 and a2, so all a1, a2 and result - are three different objects. Why? Stepping deep into the debugger I see that at this line "ts.remove(result)" my debugger jumps into my implemented AComparator. Why, and what for? At this point I cannot understand, if my implementation is corrupt, or explain why the element is not deleted from the set and the program jumps to my AComparator.
The second point, - do elements of the TreeSet stay sorted, if I change the value of the 7. attribute of an already present element? I have noticed that added elements are put in with sorting, but I haven't mentioned that changing the value of the 7. attribute influences the elements' position in the TreeSet, hence the TreeSet seems not to be a sorted set anymore. I can mistake, but, unfortunately, I cannot track this point due to the complexity of my program.
Thank you.