java利用Comparator接口对自定义数组排序
 1 import java.util.Arrays;
 2 import java.util.Comparator;
 3 
 4 public class MySort {
 5 
 6     public static void main(String[] args) {
 7         // TODO Auto-generated method stub
 8 
 9         Point[] parray = new Point[3];
10         for(int i = 2;i >= 0;i --){
11             parray[i] = new Point();
12             parray[i].x = i;
13             parray[i].y = i + 2;
14         }
15         
16         Arrays.sort(parray,new PointComparator());
17         
18         for(int i = 0;i < 3;i ++){
19             System.out.println("parray[i].x = " + parray[i].x + " "  + "parray[i].y =" + parray[i].y);
20         }
21     }
22 
23 }
24 
25 class Point{
26    int x,y;
27 }
28 
29 
30 class PointComparator implements Comparator{
31 
32     @Override
33     public int compare(Object o1, Object o2) {
34         // TODO Auto-generated method stub
35         Point p1 = (Point)o1;
36         Point p2 = (Point)o2;
37         
38         if (p1.x != p2.x) 
39             return p1.x > p2.x ? 1 : -1;   //升序
40         else
41             return p1.y > p2.y ? 1 : -1;
42                 
43         
44     }
45     
46 }

 

posted on 2017-09-25 10:29  Stephenatalie  阅读(832)  评论(0编辑  收藏  举报