简体   繁体   English

Java / Sort数组包含点

[英]Java/ Sort array which contain points

I have array with points: Point[] p = new Point[] 我有点数组: Point[] p = new Point[]

I want to sort it by x, and then by y. 我想按x排序,然后按y排序。 Meaning, If I have 意思是,如果我有

Point A = (1, 2)
Point B = (2, 1)
Point C = (1, 3)
Point D = (2, 2)

After sorting, I will get: [(1,2), (1,3), (2,1), (2,2)] 排序后,我将得到: [(1,2), (1,3), (2,1), (2,2)]

I try to use Arrays.sort() , but point isn't comparable. 我尝试使用Arrays.sort() ,但要点是不可比的。 There is an easy way to do that? 有一个简单的方法吗?

You can use Arrays.sort with a custom Comparer<Point> : 您可以将Arrays.sort与自定义的Comparer<Point>

Arrays.sort(p, new Comparator<Point>() {
    int compare(Point a, Point b) {
        int xComp = Integer.compare(a.x, b.x);
        if(xComp == 0)
            return Integer.compare(a.y, b.y);
        else
            return xComp;
    }
});

Sidenotes: 旁注:

  • If some of your Point objects may be null , you must handle this in compareTo . 如果某些Point对象可能为null ,则必须在compareTo处理。
  • If your Point is not an AWT point but your own class, you'd better let it implement Comparable . 如果您的Point不是AWT点,而是您自己的类,则最好让它实现Comparable

Let Point implement the Comparable interface, and override its compareTo method to suit your needs. Point实现Comparable接口,并覆盖其compareTo方法以满足您的需求。

    @Override
    public int compareTo(Point p) {
      if (this.x != p.x) {
        return Integer.compareTo(this.x, p.x);
      } else {
        return Integer.compareTo(this.y, p.y);
      }
    }

Read more: http://javarevisited.blogspot.com/2012/01/how-to-sort-arraylist-in-java-example.html#ixzz2S2i9k5V3 了解更多: http : //javarevisited.blogspot.com/2012/01/how-to-sort-arraylist-in-java-example.html#ixzz2S2i9k5V3

This requires editing the Point class. 这需要编辑Point类。 If that's not possible, see other answers for alternative solutions. 如果不可能,请参阅其他答案以获取替代解决方案。

you can try (pseudo code). 您可以尝试(伪代码)。

   Arrays.sort(p, new Comparator<Point >() {
        public int compare(Point p1, Point p2) {

             //here operations and return
        }
    });

Since Point does not implement comparable you can create your own class for comparison: 由于Point无法实现可比性,因此您可以创建自己的类进行比较:

public class Sorter implements Comparator 
{
  public int compare(Object o1, Object o2)
  {
    Point pointOne = (Point)o1;
    Point pointTwo = (Point)o2;
    return ((pointOne.getX()+pointOne.getY())+"").compareTo(((pointTwo.getX()+pointTwo.getY())+""));
  }
}

Then yo can use this Sorter class: 然后您可以使用此Sorter类:

void mySortingFunc(Point[] points)
{
  Arrays.sort(points, new Sorter());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM