Java如何使用逻辑有缺陷的比较器正确地对此ArrayList进行排序?

问题描述 投票:0回答:1

[在进行分配时,我发现对于以下代码,Java使用SlopeOrder比较方法中的第二个if语句,可以正确地(根据比较器中的条件)对点的ArrayList进行排序。当a> b告诉Java两个点相等时,Java如何正确地对这些点进行排序?

public class Point implements Comparable<Point>
{
   ...

   public Comparator<Point> slopeOrder() 
   {
       return new SlopeOrder();
   }

   private class SlopeOrder implements Comparator<Point> 
   {
      public int compare(Point o1, Point o2) 
      {
         double a = slopeTo(o1);
         double b = slopeTo(o2);
         if (a < b) return -1;
         if (a > b) return +1; // <--- Can be removed and list will still be sorted correctly
         return 0;
      }
   }

   ...

   public static void main(String[] args)
   {
      ArrayList<Point> points = new ArrayList<Point>();

      points.add(new Point(1,1));
      points.add(new Point(4,6));
      points.add(new Point(6,6));
      points.add(new Point(3,9));
      points.add(new Point(0,0));
      points.add(new Point(5,2));

      Point origin = new Point(0,0);
      Collections.sort(points, origin.slopeOrder());
      System.out.println(points);
   }
}

注:lopellTo只返回给定点(在这种情况下为原点)到坐标平面上其他点的斜率

输出:

[(0, 0), (5, 2), (1, 1), (6, 6), (4, 6), (3, 9)]
java comparator comparable
1个回答
0
投票
这是一个巧合。
© www.soinside.com 2019 - 2024. All rights reserved.