1. 重写Arrays.sort

Arrays.sort默认按升序进行排序。降序排列需要自己实现Comparator接口。而且有时候有两个坐标的时候的排序,也需要实现Comparator接口。

   public static void main(String[] args) {

       class point {
           private int x;
           private int y;
           public point(int x, int y) {
               this.x = x;
               this.y = y;
           }
       }
       point[] points = new point[5];
       Double d;
       int r_x, r_y;
       for (int i = 0 ; i < 5; i++) {
           d = Math.random();
           r_x = (int)(d * 10);
           d = Math.random();
           r_y = (int)(d * 10);
           points[i] = new point(r_x, r_y);
       }
       Arrays.sort(points, new Comparator<point>() {
           @Override
           public int compare(point o1, point o2) {
               if (o1.x == o2.x)
                   return o2.y - o1.y;  //按y降序排列
               return o1.x - o2.x;   //按x升序排列
           }
       });
       for (point p : points)
           System.out.println("[" + p.x +"," + p.y + "]");

       int[][] nums = {{4,3},{2,7},{8,1}};
       Arrays.sort(nums, new Comparator<int []>() {
           public int compare(int[] a, int[] b) {
               if (a[0] == b[0])
                   return a[1] - b[1];
               else
                   return a[0] - b[0];
           }
       });
View Code

相关文章:

  • 2021-10-02
  • 2021-09-22
  • 2022-12-23
  • 2022-01-02
  • 2021-05-10
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-05-10
  • 2021-06-16
  • 2021-04-20
  • 2021-12-20
  • 2021-09-06
  • 2022-12-23
相关资源
相似解决方案