import java.util.*;
/*
TreeSet集合内部实现了排序
1. 自定义对象需要实现Comparable接口的compareTo方法,自定义排序规则,return 1(第一个元素大于第二个元素),0(相等),-1(小于)
【正数负数均可,不一定要是1或者-1】
2. 如果元素本身的排序规则不适用,那么自定义比较器实现Comparator接口,并在初始化集合的时传入。
3. 底层数据结构是二叉树,大于放右边,小于放左边
*/
class TreeSetDemo {
public static void main(String[] args) {
TreeSet ts = new TreeSet(new Mycompare());
// ts.add(new People("张三",3));
// ts.add(new People("赵一",9));
// ts.add(new People("李四",4));
// ts.add(new People("王五",5));
// ts.add(new People("李四四",4));
ts.add(new People("a02",3));
ts.add(new People("a01",5));
ts.add(new People("a39",9));
ts.add(new People("a40",7));
System.out.println(ts);
Iterator i = ts.iterator();
while(i.hasNext()) {
People p = (People) i.next();
System.out.println(p.getName() + "....." + p.getAge());
}
}
}
// 元素类实现Comparable接口,复写compareTo方法
class People implements Comparable {
private String name;
private int age;
People (String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
public int getAge(){
return this.age;
}
public int compareTo (Object obj) {
People p = (People) obj;
if (this.age > p.age) {
return 1;
} else if (this.age == p.age){
return this.name.compareTo(p.name);
}
return -1;
}
}
// 比较器实现Comparator接口,复写compare方法
class Mycompare implements Comparator {
public int compare(Object o1, Object o2) {
People p1 = (People) o1;
People p2 = (People) o2;
int num = p1.getName().compareTo(p2.getName());
if (num == 0) {
return p1.getAge() - p2.getAge();
}
return num;
}
}
TreeSet集合内部排序
最新推荐文章于 2022-11-22 13:53:53 发布