Me di cuenta de que un TreeSet no mantiene los objetos mutables en orden si los valores de los atributos del objeto se modifican más adelante. Por ejemplo,Mantener los objetos mutables ordenados en TreeSets en todo momento
public class Wrap {
static TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>(){
@Override
public int compare(Student o1, Student o2) {
return o1.age - o2.age;
}
});
public static void main(String []args){
Student s = new Student(10);
ts.add(s);
ts.add(new Student(50));
ts.add(new Student(30));
ts.add(new Student(15));
System.out.println(ts);
s.age = 24; //Here I change the age of a student in the TreeSet
System.out.println(ts);
}
}
class Student{
int age;
Student(int age){
this.age = age;
}
@Override
public String toString() {
return "Student [age=" + age + "]";
}
}
La salida es:
[Student [age=10], Student [age=15], Student [age=30], Student [age=50]]
[Student [age=24], Student [age=15], Student [age=30], Student [age=50]]
Luego de cambiar la edad a un estudiante en particular y, a continuación, imprimir el TreeSet, el conjunto ya no se parece en forma ordenada. ¿Por qué pasó esto? y cómo mantenerlo ordenado siempre?
bien. ¿Alguna idea de cuál sería más rápido? – aps
Eliminar/reinsertar probablemente sea más rápido (O (log n) en comparación con O (n log n)). – aioobe
'Collections.sort' no funciona para' TreeSet' –