标签:
Collections工具类案例:
public class Student implements Comparable<Student>{ 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<Student> { @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(){ List<Integer> integerList = new ArrayList<Integer>(); 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<String> stringList = new ArrayList<String>(); 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<Student> studentList = new ArrayList<Student>(); 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(); } }
标签:
原文地址:http://blog.csdn.net/wojiaohuangyu/article/details/50901992