Treeset示例

TreeSet:可以按照添加对象的指定属性进行排序。
     即向TreeSet添加数据,必须是相同类的对象。
TreeSet里判断元素相同:如果是自然排序方式,则通过compareTo()来比较,而不是equals()和hashCode();
            如果是定制排序方式,则通过compare()来比较,而不是equals()和hashCode()

package set;

import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

/**
* @auto dh
* @create 2020-04-30-14:49
*/
class Person implements Comparable{
private String name;
private int age;

public Person(String name, int age) {
this.name = name;
this.age = age;
}

@Override
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;
}

@Override
public int compareTo(Object o) {
if(o instanceof Person){
Person person=(Person)o;
return this.name.compareTo(person.name);
}
else{
throw new RuntimeException("此类型不对");
}
}
}
public class TreeSet002 {
public static void main(String[] args) {
//自然排序
Set<Person> tset=new TreeSet<>();
tset.add(new Person("zhangsan",28));
tset.add(new Person("lisi",30));
tset.add(new Person("wangwu",21));
System.out.println(tset);
    
//定制排序
Set<Person> test1=new TreeSet<>(
new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return -Integer.compare(o1.getAge(),o2.getAge());
}
}
);
test1.add(new Person("zhangsan",28));
test1.add(new Person("lisi",30));
test1.add(new Person("wangwu",21));

System.out.println(test1);
}
}
posted @ 2020-04-30 15:14  玄空2  阅读(221)  评论(0编辑  收藏  举报