package collection;
import java.util.Comparator;
import java.util.TreeSet;
import java.util.Iterator;
public class TreeSetDemo {
/**
* |--TreeSet:可以对Set集合中的元素进行排序(按自然顺序)
* 底层数据结构是二叉树
* 保证元素唯一性的依据:compareTo方法return 0;
*
* TreeSet排序的第一种方式:让院士自身具备比较性。元素需要实现compareTo接口,覆盖compareTo方法
* 这种方式也叫做元素的自然顺序,或者叫做默认顺序
* TreeSet排序的第二种方式:当元素自身不具备比较性时,或者具备的比较性不是所需要的。
* 这时需要让集合自身具备比较性。
* 在集合初始化时,就有了比较方式。
*
* 当两种排序方式都存在时,以比较器为主
*
* 定义一个类,实现comparator接口,覆盖compare方法。
*
*
*/
public static void main(String[] args) {
TreeSet ts = new TreeSet(new MyCompare());
ts.add(new Student1("lisi02",22));
ts.add(new Student1("lisi007",20));
ts.add(new Student1("lisi007",29));
ts.add(new Student1("lisi09",19));
ts.add(new Student1("lisi08",18));
//ts.add(new Student("lisi01",40));
Iterator it = ts.iterator();
while(it.hasNext()){
Student1 stu = (Student1) it.next();
sop(stu.getName()+"..."+stu.getAge());
}
}
private static void sop(Object obj) {
System.out.println(obj);
}
}
class Student1 implements Comparable{
private String name ;
private int age;
Student1(String name,int age){
this.name = name;
this.age = age;
}
public int compareTo(Object obj){
if(!(obj instanceof Student1)){
throw new RuntimeException("不是学生对象");
}
Student1 s = (Student1) obj;
//System.out.println(this.name+"...compareTo.."+s.name);
if(this.age>s.age)
return 1;
if(this.age==s.age){
if(this.name.compareTo(s.name)>0)
return 1;
if(this.name.compareTo(s.name)<0)
return -1;
return 0;
}
else
return -1;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
class MyCompare implements Comparator{
public int compare(Object o1, Object o2){
Student1 s1 = (Student1) o1;
Student1 s2 = (Student1) o2;
int num = s1.getName().compareTo(s2.getName());
if(num == 0){
//年龄排序方法1
//return s1.getAge()-s2.getAge();
/*
*年龄排序方法2
if(s1.getAge()>s2.getAge())
return 1;
if(s1.getAge()==s2.getAge())
return 0;
return -1;
*/
//年龄排序方式3
return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
}
return num;
}
}