TreeSet是一个有顺序,且不能重复的Set集合,底层是二叉树。
TreeSet中插入多项自定义对象,要么使自定义对象具有判断顺序的方法,即实现comparable接口,重写compareTo方法,要么就实现传实现comparator的比较器的构造方法,让集合自己能对元素排序。
实现comparator比较器的构造方法如下:
package test;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
public class TestComparator {
public static void main(String[] args) {
TreeSet ts = new TreeSet(new StuComparator());
ts.add(new MyPerson("java01",1));
ts.add(new MyPerson("java04",4));
ts.add(new MyPerson("java03",3));
ts.add(new MyPerson("java02",2));
for(Iterator it = ts.iterator(); it.hasNext();)
System.out.println(it.next());
}
}
class MyPerson{
String name;
int age;
public MyPerson(String name,int age){
this.name = name;
this.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 String toString() {
return "姓名:"+this.name+",年龄:"+this.age;
}
}
class StuComparator implements Comparator{
@Override
public int compare(Object obj1, Object obj2) {
if(!(obj1 instanceof MyPerson)||!(obj2 instanceof MyPerson))
throw new RuntimeException("1111");
MyPerson p1 =(MyPerson)obj1;
MyPerson p2 =(MyPerson)obj2;
if((p1.getAge()-p2.getAge())==0)
return p1.getName().compareTo(p2.getName());
else
return p1.getAge()-p2.getAge();
}
}