TreeSet如何保证元素唯一?
当compareTo方法返回0的时候集合中只有一个元素
Person类如下:
public class Person {
private String name;
private Integer age;
public Person() {
}
public Person(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "[name=" + this.name + ",age=" + this.age + "]";
}
}
测试代码:
public class Test001 {
public static void main(String[] args) throws Exception {
Person p1 = new Person("zhangsan",23);
Person p2 = new Person("lisi",27);
Person p3 = new Person("lisi",27);
Person p4 = new Person("wangwu",25);
TreeSet<Person> tree = new TreeSet<Person>();
tree.add(p1);
tree.add(p2);
tree.add(p3);
tree.add(p4);
System.out.println(tree.size());
System.out.println(tree);
}
}
执行测试代码:
com.heima.jedis.Person cannot be cast to java.lang.Comparable
Person类实现 Comparable
public class Person implements Comparable<Person>{
private String name;
private Integer age;
public Person() {
}
public Person(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "[name=" + this.name + ",age=" + this.age + "]";
}
@Override
public int compareTo(Person o) {
int length = this.name.length() - o.name.length(); //比较长度为主要条件
int num = length == 0 ? this.name.compareTo(o.name) : length; //比较内容为次要条件
return num == 0 ? this.age - o.age : num; //比较年龄为次要条件
//这边return 0,TreeSet只能添加一个元素而已
//由此可见,TreeSet是通过compareTo控制元素
//return 0;
}
}
结果:
添加了4个Person
Person p1 = new Person("zhangsan",23);
Person p2 = new Person("lisi",27);
Person p3 = new Person("lisi",27);
Person p4 = new Person("wangwu",25);
但是new Person("lisi",27);只添加了一个,因为当添加第二个new Person("lisi",27);compareTo返回 0 ,不添加;
通过另一中方式,添加TreeSet:
public class Test001 {
public static void main(String[] args) throws Exception {
Person p1 = new Person("zhangsan",23);
Person p2 = new Person("lisi",27);
Person p3 = new Person("lisi",33);
Person p4 = new Person("wangwu",25);
TreeSet<Person> tree = new TreeSet<Person>(new CompareByLen());
tree.add(p1);
tree.add(p2);
tree.add(p3);
tree.add(p4);
System.out.println(tree.size());
System.out.println(tree);
}
}
class CompareByLen implements Comparator<Person> {
@Override
public int compare(Person o1, Person o2) {
return o1.getName().compareTo(o2.getName());
}
}
结果:
Person p3 = new Person("lisi",33);没有添加,因为通过比较name,当添加第二个lisi的时候,compare返回0,不添加。