Junior — Middle
What are the requirements for objects in TreeSet for proper sorting and operation in Java?
sobes.tech AI
Answer from AI
For correct operation and sorting in TreeSet, objects must meet the following requirements:
-
Implement the Comparable interface or be comparable via a Comparator passed to the TreeSet constructor. This is necessary for TreeSet to order the elements.
-
Follow the comparison contract: the
compareTo(orcompare) method must be consistent withequals. That is, ifcompareTo(a, b) == 0, then the objects are considered equal and cannot both be stored in the TreeSet. -
Objects should be immutable with respect to the fields involved in comparison. If the fields affecting the order change after being added to the TreeSet, it will break the structure and lead to incorrect behavior.
Example:
class Person implements Comparable<Person> {
String name;
int age;
public int compareTo(Person other) {
return this.name.compareTo(other.name);
}
}
TreeSet<Person> set = new TreeSet<>();
set.add(new Person("Alice", 30));
set.add(new Person("Bob", 25));
In this example, sorting occurs by name.