package cn.itcast_02; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /* * Collections可以针对ArrayList存储基本包装类的元素排序,存储自定义对象可不可以排序呢? * */ public class CollectionsDemo { public static void main(String[] args) { // 创建集合对象 List<Student> list = new ArrayList<Student>(); // 创建学生对象 Student s1 = new Student("张三", 25); Student s2 = new Student("李四", 22); Student s3 = new Student("王五", 30); Student s4 = new Student("李四", 22); // 添加元还给 list.add(s1); list.add(s2); list.add(s3); list.add(s4); // 排序 // 自然排序 // Collections.sort(list); // 比较器排序 // 如果同时有自然排序和比较器排序,以比较器排序为主 Collections.sort(list, new Comparator<Student>() { @Override public int compare(Student s1, Student s2) { int num = s2.getAge() - s1.getAge(); int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num; return num2; } }); List<Student> Newlist = new ArrayList<Student>(); for (int x = 0; x < list.size(); x++) { Student stu = list.get(x); if (!Newlist.contains(stu)) { Newlist.add(stu); } } // 遍历集合 for (Student stu : Newlist) { System.out.println(stu.getName() + "---" + stu.getAge()); } } }
package cn.itcast_02; public class Student implements Comparable<Student> { private String name; private int age; public Student() { super(); // TODO Auto-generated constructor stub } 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; } @Override public int compareTo(Student s) { int num = this.age - s.age; int num2 = num == 0 ? this.name.compareTo(s.name) : num; return num2; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Student other = (Student) obj; if (age != other.age) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }