有两种方式,第一种同楼上的,用comparable
第二种可以用接口comparator比较器接口实现。如下
class GenericDemo3
{
public static void main(String[] args)
{
//Student s = new Student();
TreeSet<Student> tree = new TreeSet<Student>(new Comparator<Student>(){
@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
int num = o1.getName().length()-o2.getName().length();
int num2=(num==0)?(o1.getAge()-o2.getAge()):num;
int num3=(num2==0)?o1.getName().compareTo(o2.getName()):num2;
return num3;
}
});
ts.add(new Student("lisi01"));
ts.add(new Student("lisi02"));
ts.add(new Student("lisi03"));
Iterator<Student> it = ts.iterator();
while (it.hasNext())
{
System.out.println(it.next().getName());
}
/*Student s = new Student("lisi001");
System.out.println(s.getName());*/
Iterator<Student> it = ts.iterator();
while (it.hasNext())
{
System.out.println(it.next().getName());
}
/*Student s = new Student("lisi001");
System.out.println(s.getName());*/
|