java如何对ArrayList中对象按照该对象某属性排序
展开全部
if(!s1.name.equals(s2.name)){
return s2.name.compareTo(s1.name);}else{//姓名也相同则按学号排序
return s2.id-s1.id;}}}};Student stu1 = new Student (1,"zhangsan","male",28,"cs");
Student stu2 = new Student (2,"lisi","female",19,"cs");
Student stu3 = new Student (3,"wangwu","male",22,"cs");
Student stu4 = new Student (4,"zhaoliu","female",17,"cs");
Student stu5 = new Student (5,"jiaoming","male",22,"cs"); ArrayList List = new ArrayList();
List.add(stu1);
List.add(stu2);
List.add(stu3);
List.add(stu4);
List.add(stu5);
//这里就会自动根据规则进行排序
Collections.sort(List,comparator);
display(List);}
static void display(ArrayList lst){
for(Student s:lst)
System.out.println(s);}} class Student{int age;int id;String gender;
String name;String cs;Student(int id,String name,String gender,int age,String cs){
this.age=age;
this.name=name;
this.gender=gender;
this.id=id;
return id+" "+name+" "+gender+" "+age+" "+cs;}} 2.添加 Comparable 接口,重写 compareTo 方法。然后你可以用 TreeSet 结构进行排序。它会自动排序。
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询