对集合进行排序

发布时间:2016-12-8 13:53:00 编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"对集合进行排序",主要涉及到对集合进行排序方面的内容,对于对集合进行排序感兴趣的同学可以参考一下。

public class Test { public static void main(String []args){ List<People> list = new ArrayList<People>(); People p1 = new People("zs","32"); People p2 = new People("ls","20"); People p3 = new People("ww","22"); People p4 = new People("ws","22"); list.add(p1); list.add(p2); list.add(p3); list.add(p4); PeopleCom pc = new PeopleCom(); Collections.sort(list,pc); for(People p:list){ System.out.print(p.getName()+p.getAge()+"   "); } } } class PeopleCom implements Comparator{ public int compare(Object o1, Object o2) { // TODO Auto-generated method stub People p1 = (People)o1; People p2 = (People)o2; int flag = p1.getAge().compareTo(p2.getAge()); if(flag == 0){ return p1.getName().compareTo(p2.getName()); } return flag; } } class People{ private String name; private String age; public People(String name,String age){ this.name = name; this.age = age; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } } 1.定义比较对象People 2.PeopleCom实现Comparator接口,定义比较规则 3.比较调用PeopleCom pc = new PeopleCom();Collections.sort(list,pc);

上一篇:FatMouse' Trade
下一篇:迪米特法则

相关文章

相关评论