方法一:實現Comparable接口排序package collsort.comparable;
package com.cvicse.sort.comparable;
public class Cat implements Comparable<Cat> {
private int age;
private String name;
public Cat(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
......
public int compareTo(Cat o) {
return this.getAge() - o.getAge();
}
......
}
通過實現Comparable接口實現個性化排序測試。排序測試,Collection.sort(list)升序排列Collections.sort(list, Collections.reverseOrder());降序排列;Collections.reverse(list);反轉排序,先輸出列表最后一個元素
public class TestComparable {
public static void main(String args[]) {
test();
test2();
}
public static void test() {
......
List<Cat> listCat1 = new ArrayList<Cat>();
Cat cat1 = new Cat(34, "hehe");
Cat cat2 = new Cat(12, "haha");
Cat cat3 = new Cat(23, "leizhimin");
Cat cat4 = new Cat(13, "lavasoft");
listCat1.add(cat1);
listCat1.add(cat2);
listCat1.add(cat3);
......
System.out.println("調用Collections.sort(List<T> list)listCat2升序排序:");
Collections.sort(listCat1);
System.out.println("降序排列元素:");
Collections.sort(listCat1, Collections.reverseOrder());
System.out.println("Collections.reverse 從列表中最后一個元素開始輸出:");
Collections.reverse(listCat1);
......
}
/**
* 針對數組的排序
*/
public static void test2() {
String[] strArray = new String[] { "z", "a", "C" };
System.out.println("數組轉換為列表");
List<String> list = Arrays.asList(strArray);
System.out.println("順序排序列表");
Collections.sort(list);
System.out
.println("按String實現的Comparator對象String.CASE_INSENSITIVE_ORDER排序----");
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
System.out.println("倒序排序列表");
Collections.sort(list, Collections.reverseOrder());
......
}
}
方法二:實現Comparator接口排序
public class Person {
private int age;
private String name;
......
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
......
}
實現了Comparator接口,重寫了compare方法
import java.util.Comparator;
public class PersonComparator implements Comparator<Person> {
public int compare(Person o1, Person o2) {
return o1.getAge() - o2.getAge();
}
}
測試方法
public class TestComparator {
public static void main(String args[]) {
test1();
}
public static void test1() {
System.out.println("升序排序測試:");
List<Person> listPerson = new ArrayList<Person>();
Person person1 = new Person(34, "lavasoft");
Person person2 = new Person(12, "lavasoft");
Person person3 = new Person(23, "leizhimin");
Person person4 = new Person(13, "sdg");
listPerson.add(person1);
listPerson.add(person2);
listPerson.add(person3);
Comparator<Person> ascComparator = new PersonComparator();
System.out.println("排序后集合為:");
// 利用Collections類靜態工具方法對集合List進行排序
Collections.sort(listPerson, ascComparator);
System.out.println("\n降序排序測試:");
// 從升序排序對象產生一個反轉(降序)的排序對象
Comparator<Person> descComparator = Collections
.reverseOrder(ascComparator);
System.out.println("利用反轉后的排序接口對象對集合List排序並輸出:");
Collections.sort(listPerson, descComparator);
outCollection(listPerson);
}
}