package com.day14.wd;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] ag){
TreeSet ts=new TreeSet(new MyCompare());
ts.add(new Student("lisi", 123));
ts.add(new Student("wangwu", 23));
ts.add(new Student("wef",23));
Iterator it=ts.iterator();
while (it.hasNext()) {
Student ss = (Student) it.next();
System.out.println("name"+ss.getName()+",age"+ss.getAge());
}
}
}
class MyCompare implements Comparator{
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
Student p1=(Student)o1;
Student p2=(Student)o2;
//保证唯一性,返回0;
int num=p1.getAge()-p2.getAge();
if(num==0){
return p2.getName().compareTo(p2.getName());
}//String实现了compareTo()方法
return num ;
}
}
class Student {
private String name;
private int age;
public Student(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;
}
}