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(3);
list.add(1);
list.add(2);
//自然顺序
Collections.sort(list);
for(Integer i:list){
System.out.println(i);
}
System.out.println("===============================================");
Point point2 = new Point(2,2,2);
Point point1 = new Point(1,1,1);
Point point3 = new Point(3,1,2);
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());
}
}
}
降序输出类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;
}
}
}
升序输出类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;
}
}
}
posted on 2011-06-22 16:03
secret_x15 阅读(6477)
评论(1) 编辑 收藏 所属分类:
java