第一种
/* * Collections可以针对ArrayList存储基本包装类的元素排序,存储自定义对象可不可以排序呢? */public class CollectionsDemo { public static void main(String[] args) { // 创建集合对象 List<Student> list = new ArrayList<Student>(); // 创建学生对象 Student s1 = new Student("linqingxia", 27); Student s2 = new Student("风清扬", 30); Student s3 = new Student("刘晓曲", 28); Student s4 = new Student("武鑫", 29); Student s5 = new Student("caiming", 27); // 添加元素对象 list.add(s1); list.add(s2); list.add(s3); list.add(s4); list.add(s5); // 排序 // 自然排序 // Collections.sort(list); // 比较器排序 // 如果同时有自然排序和比较器排序,以比较器排序为主 Collections.sort(list, new Comparator<Student>() { @Override public int compare(Student s1, Student s2) { if(s1.getAge()-(s2.getAge())!=0){ return s1.getAge()-(s2.getAge()); }else{ return s1.getName().compareTo(s2.getName()); } } }); // 遍历集合 for (Student s : list) { System.out.PRintln(s.getName() + "---" + s.getAge()); } }}public class Student { private String name; private int age; public Student() { super(); } public Student(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; }}第二种public class User { private int age; private String name; public User(String name,int age){ this.name=name; this.age=age; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; }} //具体的比较类,实现Comparator接口 public class ComparatoUser implements Comparator { public int compare(Object arg0, Object arg1) { User user0=(User)arg0; User user1=(User)arg1;// 首先比较年龄,如果年龄相同,则比较名字 int flag=user0.getAge()-(user1.getAge()); if(flag==0){ return user0.getName().compareTo(user1.getName()); }else{ return flag; } }} //测试类 public class TestUser { public static void main(String[] args){ List list=new ArrayList(); list.add(new User("aa",12)); list.add(new User("dd",888)); list.add(new User("ff",123)); list.add(new User("cc",123)); list.add(new User("bb",142)); list.add(new User("ww",126)); 主要看看拿的那个对象 ComparatoUser com=new ComparatoUser(); Collections.sort(list, com); for(int i=0;i<list.size();i++){ User u=(User)list.get(i); System.out.print(u.getAge()+"/"); System.out.println(u.getName()); } }}
新闻热点
疑难解答