import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSet1 {
public static void main(String[] args) {
TreeSet<Person> t=new TreeSet<Person>(new Comparator1());
t.add(new Person("mary",21));
t.add(new Person("jounp",23));
t.add(new Person("junpew",21));
t.add(new Person("helloworld",24));
Iterator<Person> it=t.iterator();
while(it.hasNext())
{
System.out.println(it.next().getName().toString());
}
}
}
class Person {
private String name;;
private int age;
public Person(String name,int age)
{
this.name=name;
this.age=age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
class Comparator1 implements Comparator {
@Override
public int compare(Object o1, Object o2) {
Person p1=(Person)o1;
Person p2=(Person)o2;
int temp=p1.getName().length()-p2.getName().length();
return temp==0?p1.getName().compareTo(p2.getName()):temp;
}
}
修改下红色部分就可以
程序有点乱 |
|