【问题标题】:Sorting a list of points with Java [duplicate]用Java对点列表进行排序[重复]
【发布时间】:2011-07-07 21:04:37
【问题描述】:

我有一个点对象列表,我想按某个坐标对其进行排序,比如 x 值。 Java 是否提供了任何有用的机制,还是我应该利用其中一种常见的排序算法?

【问题讨论】:

    标签: java sorting


    【解决方案1】:

    是的,创建一个自定义 Comparator ,并使用它对点列表进行排序

    class Point{
        private int x;
        private int y;
    
        public int getX() {
            return x;
        }
    
        public void setX(int x) {
            this.x = x;
        }
    
        public int getY() {
            return y;
        }
    
        public void setY(int y) {
            this.y = y;
        }
    
        public Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
    
        public Point() {
        }
    }
    

    List<Point> points = new ArrayList<Point>();
    points.add(new Point(1, 2));
    points.add(new Point(60, 50));
    points.add(new Point(50, 3));
    Collections.sort(points,new Comparator<Point>() {
    
    public int compare(Point o1, Point o2) {
        return Integer.compare(o1.getX(), o2.getX());
    }
    });
    

    【讨论】:

      【解决方案2】:

      Point 类中,您应该使用泛型类型&lt;Point&gt; 实现Comparable 接口,并使用Collections.sort(java.util 包)对List&lt;Point&gt; 进行排序

      假设:

      class Point implements Comparable<Point>{
          int compareTo(Point other){ /* your logic */}
      }
      
      List<Point> list = new ArrayList<Point>();
      /* adding points */
      Collections.sort(list);
      

      【讨论】:

        【解决方案3】:

        您应该让您的点类实现 Comparable 接口,或者为您自己的 Comparator 对象提供 sort() 方法,该方法告诉 sort() 如何对您的对象进行排序。这里有很多例子。

        【讨论】:

          【解决方案4】:

          您可以使用Bean Comparator 之类的东西,这样您就不必继续创建自定义比较器。

          【讨论】:

            猜你喜欢
            • 2014-10-27
            • 1970-01-01
            • 2021-09-28
            • 2014-12-26
            • 1970-01-01
            • 1970-01-01
            • 2021-08-21
            • 1970-01-01
            • 2013-07-09
            相关资源
            最近更新 更多