标签:bsp 包装 public cad 自定义对象 compareto iso std override
ListDemo2.java ----------------- package com.fs.test; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /* * Collections可以针对ArrayList存储基本包装类的元素排序,存储自定义对象可不可以排序呢? */ public class Listdemo2 { public static void main(String[] args) { // 创建集合对象 List<Person2> list = new ArrayList<Person2>(); Person2 s1 = new Person2("Bobby",18); Person2 s2 = new Person2("Mike",20); Person2 s3 = new Person2("Jim",35); Person2 s4 = new Person2("Zoe",27); Person2 s5 = new Person2("Dave",18); Person2 s6 = new Person2("Madison",35); Person2 s7 = new Person2("Caden",40); Person2 s8 = new Person2("Ava",23); Person2 s9 = new Person2("Noah",25); Person2 s10 = new Person2("Isabella",27); Person2 s11 = new Person2("Lucas",25); // 添加元素对象 list.add(s1); list.add(s2); list.add(s3); list.add(s4); list.add(s5); list.add(s6); list.add(s7); list.add(s8); list.add(s9); list.add(s10); list.add(s11); // 排序 // 自然排序 // Collections.sort(list); // 比较器排序 // 如果同时有自然排序和比较器排序,以比较器排序为主 Collections.sort(list, new Comparator<Person2>() { @Override public int compare(Person2 s1, Person2 s2) { if(s1.getAge()-(s2.getAge())!=0){ return s1.getAge()-(s2.getAge()); }else{ return s1.getName().compareTo(s2.getName()); } } }); // 遍历集合 for (Person2 s : list) { System.out.println(s.getName() + "---" + s.getAge()); } } } Person2,java -------------------package com.fs.test; public class Person2 { private String name; private int age; public Person2() { super(); } public Person2(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
对ArrayList中的Person对象按照先年龄从大到小,相同年龄的再按照姓名(姓名是英文的)的字母顺序进行排序.
标签:bsp 包装 public cad 自定义对象 compareto iso std override
原文地址:https://www.cnblogs.com/ooo888ooo/p/11144916.html