案例:
public class Student implements Comparable{ String id; String name; public Student(String ID, String st_Name) { // TODO Auto-generated constructor stub this.id = ID; this.name = st_Name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int compareTo(Student o) { // TODO Auto-generated method stub return this.id.compareTo(o.id); } }
public class StudentComparator implements Comparator{ @Override public int compare(Student arg0, Student arg1) { // TODO Auto-generated method stub return arg0.name.compareTo(arg1.name); } }
public class CollectionTest { /** * 通過Collections.sort()方法,對Integer泛型的List進行排序 * */ public void testSort1(){ ListintegerList = new ArrayList (); Random random = new Random(); Integer k; for(int i = 0; i < 10;i++){ do{ k = random.nextInt(100); }while(integerList.contains(k)); integerList.add(k); System.out.println("成功添加整數:" + k); } System.out.println("排序前--------------------"); for (Integer integer : integerList) { System.out.println("元素:" + integer); } Collections.sort(integerList); System.out.println("排序後---------------------"); for (Integer integer : integerList) { System.out.println("元素:" + integer); } } /* * 對String泛型的List進行排序 * * */ public void testSort2(){ List stringList = new ArrayList (); stringList.add("del"); stringList.add("lenovo"); stringList.add("ios"); stringList.add("apple"); System.out.println("排序前----------------"); for(String string:stringList){ System.out.println("元素:" + string); } Collections.sort(stringList); System.out.println("排序後------------------"); for(String string:stringList){ System.out.println("元素:" + string); } } /* * 對其他類型的泛型List進行排序 * */ public void testSort3(){ List studentList = new ArrayList (); Random random = new Random(); studentList.add(new Student(random.nextInt(1000) + "","xiaoming")); studentList.add(new Student(random.nextInt(1000) + "","xiaohong")); studentList.add(new Student(random.nextInt(1000) + "","xiaobing")); studentList.add(new Student(random.nextInt(1000) + "","abcde")); System.out.println("排序前-------------"); for (Student student : studentList) { System.out.println("學生:" + student.id + " "+ student.name); } Collections.sort(studentList); System.out.println("排序後------------"); for (Student student : studentList) { System.out.println("學生:" + student.id + " "+ student.name); } Collections.sort(studentList,new StudentComparator()); System.out.println("按照姓名排序後-------------"); for (Student student : studentList) { System.out.println("學生:" + student.id + " "+ student.name); } } public static void main(String[] args) { // TODO Auto-generated method stub CollectionTest ct = new CollectionTest(); // ct.testSort1(); // ct.testSort2(); ct.testSort3(); } }