Java ArrayList 排序 – JAVA編程語言程序開發技術文章

import java.util.*;    
   
public class Test {    
   
public static void main(String[] args){    
  List<Point> points=new ArrayList<Point>();    
      
  Point point1=new Point();    
  point1.setX(1324);    
  point1.setY(345);    
  point1.setZ(436);    
  points.add(point1);    
      
  Point point2=new Point();    
  point2.setX(23);    
  point2.setY(8941.656);    
  point2.setZ(431412);    
  points.add(point2);    
      
  Point point3=new Point();    
  point3.setX(786584);    
  point3.setY(23452);    
  point3.setZ(43563);    
  points.add(point3);    
      
  //根據X排序    
  Collections.sort(points,new SortByX());    
      
  for(Point p:points){    
   System.out.print(p.getX()+"\t"+p.getY()+"\t"+p.getZ());    
   System.out.println();    
  }    
      
  //根據Y排序    
//  Collections.sort(points,new SortByY());    
//      
//  for(Point p:points){    
//   System.out.print(p.getX()+"\t"+p.getY()+"\t"+p.getZ());    
//   System.out.println();    
//  }    
//      
//  //根據Z排序    
//  Collections.sort(points,new SortByZ());    
//      
//  for(Point p:points){    
//   System.out.print(p.getX()+"\t"+p.getY()+"\t"+p.getZ());    
//   System.out.println();    
//  }    
}    
   
}    
   
class Point{    
private double x;    
private double y;    
private double z;    
public double getX() {    
  return x;    
}    
public void setX(double x) {    
  this.x = x;    
}    
public double getY() {    
  return y;    
}    
public void setY(double y) {    
  this.y = y;    
}    
public double getZ() {    
  return z;    
}    
public void setZ(double z) {    
  this.z = z;    
}    
public Point(){}    
}    
   
//根據X排序    
class SortByX implements Comparator{    
public int compare(Object obj1,Object obj2){    
  Point point1=(Point)obj1;    
  Point point2=(Point)obj2;    
  if(point1.getX()>point2.getX())    
   return 1;    
  else   
   return 0;    
}    
}    
//根據Y排序    
class SortByY implements Comparator{    
public int compare(Object obj1,Object obj2){    
  Point point1=(Point)obj1;    
  Point point2=(Point)obj2;    
  if(point1.getY()>point2.getY())    
   return 1;    
  else   
   return 0;    
}    
}    
//根據Z排序    
class SortByZ implements Comparator{    
public int compare(Object obj1,Object obj2){    
  Point point1=(Point)obj1;    
  Point point2=(Point)obj2;    
  if(point1.getZ()>point2.getZ())    
   return 1;    
  else   
   return 0;    
}    
}     

摘自 laiconglin的專欄

發佈留言