// 新建链表并加入元素
List<Member> members=new ArrayList<Member>();
members.add(new Member("Andy",20));
members.add(new Member("Dell",23));
members.add(new Member("Felex",24));
members.add(new Member("Bill",21));
members.add(new Member("Cindy",22));
// 创建一个比较器匿名类
Comparator comparator=new Comparator(){
public int compare(Object op1,Object op2){
Member memberOp1=(Member)op1;
Member memberOp2=(Member)op2;
// 按姓名排序
return memberOp1.getName().compareTo(memberOp2.getName());
}
};
// 排序
Collections.sort(members,comparator);
// 输出排序后的链表
for(Member member:members){
System.out.println(member.getName() + ":" + member.getAge());
}
}
输出结果:
Andy:20
Bill:21
Cindy:22
Dell:23
Felex:24