转自 http://blog.csdn.net/a1165117473/article/details/6965652
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.city.test;
import java.util.Arrays;
import java.util.Comparator;
/**
*
* @author LiuB
*/
public class sortTesty {
//对整数集合进行排序
public void sortIntArray() {
int[] array = new int[] { 8, 5, 9, 0, 6, 3, 4, 7, 2, 1 };
System.out.println("整数排序前");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
Arrays.sort(array);
System.out.println("整数排序后");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
}
//对字符串集合进行排序
public void sortStringArray() {
String[] array = new String[] { "a", "c", "e", "d", "b" };
System.out.println("字符串排序前");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
System.out.println("字符串排序后");
Arrays.sort(array);
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
}
//对集合进行排序
java对集合排序的方法主要有两种,分别为实现Comparator接口和实现Comparable接口。其中,实现Comparable接口比较简单,用于单一标准的排序。如:
public class Animals implements Comparable<Animals>{
private String name;
public int age;
public Animals(String name, int age) {
this.name = name;
this.age = age;
}
public static void main(String[] args) {
LinkedList<Animals> list = new LinkedList<Animals>();
list.add(new Animals("a", 2));
list.add(new Animals("b", 4));
list.add(new Animals("c", 6));
Collections.sort(list);//需重写compareTo()方法
for (Animals animals : list) {
System.out.println("Animals name=" + animals.name + "age="
+ animals.age);
}
}
@Override
public int compareTo(Animals o) {
if (this.age > o.age)
return 1;
if (this.age < o.age)
return -1;
else
return 0;
}
}
但如果要实现多种要求的排序,就要实现Comparator接口了。因为Comparable接口只能用一种方式比较。实现Comparator接口,如:
Collections.sort(list, new AnimalsComparator());//sort方法的两个参数:比较的集合,比较器类的对象。
//比较器类,实现compare()方法
class AnimalsComparator implements Comparator<Animals> {
@Override
public int compare(Animals o1, Animals o2) {
if (o1.age > o2.age)
return 1;
if (o1.age < o2.age)
return -1;
else
return 0;
}
}
这样,通过构建不同的比较器类,并在sort()方法里面传入不同的比较器类对象,就能实现对象的不同属性比较。上面是按年龄,如果按体重也可以,如:
Collections.sort(list, new AnimalsWeightComparator());
class AnimalsWeightComparator implements Comparator<Animals> {
@Override
public int compare(Animals o1, Animals o2) {
if (o1.weight> o2.weight)
return 1;
if (o1.weight< o2.weight)
return -1;
else
return 0;
}
}
当然PO类要有对应的属性,并为属性传入参数。