public class Person implements Comparable<Person> {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int compareTo(Person o) {
int ageGap = this.age - o.age;
int nameGap = this.name.compareTo(o.name);
return ageGap != 0 ? ageGap : nameGap;
// return nameGap != 0 ? nameGap : ageGap;
}
}
public class TreeSetDemo {
public static void main(String[] args) {
Set<Person> set1 = new TreeSet<Person>();
set1.add(new Person("zs", 19));
set1.add(new Person("ls", 20));
set1.add(new Person("ww", 20));
set1.add(new Person("ww", 18));
System.out.println(set1);
}
}
实现Comparable接口重写compareTo方法使用TreeSet存入重复对象后,TreeSet内部存储结构为二叉树,当存入了重复元素后内部存储结构有什么改变? |
|