1.main方法:
public class Test { public static void main(String[] args) {
/**
*
* sort()方法详解
* 1.Collections.sort(List<T> list)
* 根据元素的自然顺序 对指定列表按升序进行排序。
* 2.Collections.sort(List<T> list, Comparator<? super T> c)
* 根据指定比较器产生的顺序对指定列表进行排序。
*
*/
List<Integer> list = new ArrayList<Integer>();
list.add();
list.add();
list.add();
//自然顺序
Collections.sort(list);
for(Integer i:list){
System.out.println(i);
} System.out.println("==============================================="); Point point2 = new Point(,,);
Point point1 = new Point(,,);
Point point3 = new Point(,,); List<Point> points = new ArrayList<Point>();
points.add(point2);
points.add(point1);
points.add(point3); System.out.println("===============================================");
//根据point中的升序输出
Collections.sort(points, new SortByXdesc());
for(Point point:points){
System.out.println("x:"+point.getX()+" y:"+point.getY()+" z:"+point.getZ());
} System.out.println("===============================================");
//根据point中的x降序输出
Collections.sort(points, new SortByXasc());
for(Point point:points){
System.out.println("x:"+point.getX()+" y:"+point.getY()+" z:"+point.getZ());
}
} }
2.降序输出类SortByXdesc:
public class SortByXdesc implements Comparator<Object> { //根据point中的x降序输出
@Override
public int compare(Object o1, Object o2) {
Point point1 =(Point)o1;
Point point2 =(Point)o2;
if(point1.getX()>point2.getX()){
return 1;
}else{
return 0;
}
} }
3.升序输出类SortByXasc:
public class SortByXasc implements Comparator<Object> { //根据point中的x升序输出
@Override
public int compare(Object o1, Object o2) {
Point point1 =(Point)o1;
Point point2 =(Point)o2;
if(point1.getX()>point2.getX()){
return 0;
}else{
return 1;
}
}
}
转:http://www.blogjava.net/secret/archive/2011/12/03/352813.html