class c implements Comparator
{public c()
{}
public c(int age ,String name)
{this.age=age;this.name=name;}
int age;
String name;
public int getAge()
{return age;}
public int compare(Object arg0, Object arg1) {
c x= (c) arg0;
c y=(c)arg1;
if(x.getAge()>y.getAge())return -1;
if(x.getAge()<y.getAge())return 1;
return 0;
}
}
Set ts=new TreeSet(new c());
ts.add(new c(6,"gudalei"));
ts.add(new c(8,"zhang"));
ts.add(new c(3,"adfs"));
Iterator is=ts.iterator();
while(is.hasNext())
{System.out.println(((c)is.next()).getAge());}
{public c()
{}
public c(int age ,String name)
{this.age=age;this.name=name;}
int age;
String name;
public int getAge()
{return age;}
public int compare(Object arg0, Object arg1) {
c x= (c) arg0;
c y=(c)arg1;
if(x.getAge()>y.getAge())return -1;
if(x.getAge()<y.getAge())return 1;
return 0;
}
}
Set ts=new TreeSet(new c());
ts.add(new c(6,"gudalei"));
ts.add(new c(8,"zhang"));
ts.add(new c(3,"adfs"));
Iterator is=ts.iterator();
while(is.hasNext())
{System.out.println(((c)is.next()).getAge());}
本文展示了一个具体的Java示例,通过实现Comparator接口来比较自定义类中的成员变量年龄,并利用TreeSet完成对象集合的排序。示例中定义了一个名为classc的类,该类实现了Comparator接口,并重写了compare方法来按年龄进行比较。
1140

被折叠的 条评论
为什么被折叠?



