Java 如何对 Point 对象的 ArrayList 进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4199509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 05:17:09  来源:igfitidea点击:

Java how to sort an ArrayList of Point objects

javasortingarraylistcomparator

提问by user492837

I'm using the Point Class to manage a list of (x,y) coordinates and I need to sort them in order of X.

我正在使用 Point Class 来管理 (x,y) 坐标列表,我需要按 X 的顺序对它们进行排序。

I read online to make a new class PointCompare that implements Comparator, however I'm not sure how this works and therefore I have a compiler error in the sortByXCoordinates method.

我在线阅读以创建一个实现 Comparator 的新类 PointCompare,但是我不确定它是如何工作的,因此我在 sortByXCoordinates 方法中有一个编译器错误。

Help would be appreciated a lot, and any comments are welcome, thanks in advance. Here is some of my code:

非常感谢您的帮助,欢迎提出任何意见,提前致谢。这是我的一些代码:

import javax.swing.JOptionPane;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
//import java.util.Iterator;

public class ConvexHullMain {

 private Point coordinates = new Point(0, 0);
 private final int MAX_POINTS = 3;
 private ArrayList<Point> coordinateList = new ArrayList<Point>();

 public void inputCoordinates() {

  String tempString; // temp string for JOptionPane
  int tempx = 0;
  int tempy = 0;

  for (int i = 0; i < MAX_POINTS; i++) {
   try {
    // input x coordinates
    tempString = JOptionPane.showInputDialog(null,
      "Enter X coordinate:");
    tempx = Integer.parseInt(tempString);

    // input y coordinates
    tempString = JOptionPane.showInputDialog(null,
      "Enter Y coordinate:");
    tempy = Integer.parseInt(tempString);

    coordinates.setLocation(tempx, tempy);// set input data into
              // coordinates object
    coordinateList.add(coordinates.getLocation()); // put in
                // arrayList

   } // end Try
   catch (NumberFormatException e) {
    System.err.println("ERROR!");
    main(null);

   } // end catch

  }// end for loop

 }

 public void displayPoints() {

  for (int i = 0; i < MAX_POINTS; i++) {

   JOptionPane.showMessageDialog(null, "Point number " + (i + 1)
     + " is: " + coordinateList.get(i));

  }

  // alt method
  // Iterator i = coordinateList.iterator();
  // String outputTemp;
  // while (i.hasNext()) {
  // outputTemp = i.next().toString();
  // JOptionPane.showMessageDialog(null, "Point number " + " is: "
  // + outputTemp);
  // }

 }


 /**
  * This sorts the points by the X coordinates
  */
  public void sortByXCoordinates(){

   coordinateList.sort(coordinates, new PointCompare());
  }

   public class PointCompare implements Comparator<Point> {

   public int compare(Point a, Point b) {
    if (a.x < b.x) {
     return -1;
    } else if (a.x > b.x) {
     return 1;
    } else {
     return 0;
    }
   }
   }

   public static void main(String[] args) {
  ConvexHullMain main = new ConvexHullMain();

  main.inputCoordinates();
  main.displayPoints();


 }
}

回答by Paul Croarkin

private ArrayList<Point> coordinateList = new ArrayList<Point>();

...

...

Collections.sort(coordinateList, new PointCompare());

...

...

public class PointCompare implements Comparator<Point> {
    public int compare(Point a, Point b) {
        if (a.x < b.x) {
            return -1;
        }
        else if (a.x > b.x) {
            return 1;
        }
        else {
            return 0;
        }
    }
}

回答by Amir Afghani

You were close. The problem you had was simply that you invoked

你很接近。您遇到的问题只是您调用了

  public void sortByXCoordinates(){

   coordinateList.sort(coordinates, new PointCompare());

  }

What you want is this:

你想要的是这个:

import java.awt.Point;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import javax.swing.JOptionPane;

public class MainClass {

    private final Point coordinates = new Point(0, 0);
    private final int MAX_POINTS = 3;
    private final ArrayList<Point> coordinateList = new ArrayList<Point>();

    public void inputCoordinates() {

        String tempString;
        int tempx = 0;
        int tempy = 0;

        for (int i = 0; i < this.MAX_POINTS; i++) {
            try {
                tempString = JOptionPane.showInputDialog(null, "Enter X coordinate:");
                tempx = Integer.parseInt(tempString);
                tempString = JOptionPane.showInputDialog(null, "Enter Y coordinate:");
                tempy = Integer.parseInt(tempString);
                this.coordinates.setLocation(tempx, tempy);// set input data into
                this.coordinateList.add(this.coordinates.getLocation()); // put in
            }
            catch (final NumberFormatException e) {
                System.err.println("ERROR!");
                main(null);

            }
        }
    }

    public void displayPoints() {

        for (int i = 0; i < this.MAX_POINTS; i++) {

            JOptionPane.showMessageDialog(null, "Point number " + (i + 1) + " is: " + this.coordinateList.get(i));

        }

    }

    /**
     * This sorts the points by the X coordinates
     */
    public void sortByXCoordinates() {

        Collections.sort(this.coordinateList, new PointCompare());

    }

    public class PointCompare
        implements Comparator<Point> {

        public int compare(final Point a, final Point b) {
            if (a.x < b.x) {
                return -1;
            }
            else if (a.x > b.x) {
                return 1;
            }
            else {
                return 0;
            }
        }
    }

    public static void main(final String[] args) {
        final MainClass main = new MainClass();

        main.inputCoordinates();
        main.displayPoints();

    }
}

回答by pstanton

i'm going to ignore all of the code you posted because you've just dumped everything without taking the time to identify the relevant areas.

我将忽略您发布的所有代码,因为您只是转储了所有内容而没有花时间确定相关区域。

now, from your question: you have an ArrayListcontaining Points. You want to sort it by the X axis/value.

现在,从你的问题:你有一个ArrayList包含Points。您想按 X 轴/值对其进行排序。

List<Point> list = new ArrayList<Point>();

Firstly you need a Comparatorwhich will compare one Pointto another.

首先,您需要一个Comparator将一个人Point与另一个人进行比较的对象。

Comparator<Point> comp = new Comparator<Point>()
{
    @Override
    public int compare(Point o1, Point o2)
    {
        return new Integer(o1.x).compareTo(o2.x);
    }
};

I choose to "box" the int to an Integer and use Integer's compareTo method. You could come up with a tidier method of comparison, up to you.

我选择将 int 装箱成一个 Integer 并使用 Integer 的 compareTo 方法。你可以想出一个更整洁的比较方法,由你决定。

Then you can use the utility method Collections.sort

然后你可以使用实用方法 Collections.sort

Collections.sort(list, comp);

and your list is sorted.

并且您的列表已排序。

回答by user507787

The ArrayList class (see API documentation: http://download.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html) that you use for your 'coordinateList' does not have a sort() method. You will have to implement this yourself, or use Collections.sort().

您用于“坐标列表”的 ArrayList 类(请参阅 API 文档:http: //download.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html)没有排序( ) 方法。您必须自己实现,或使用 Collections.sort()。

回答by camickr

I'm using the Point Class to manage a list of (x,y) coordinates and I need to sort them in order of X

我正在使用 Point Class 来管理 (x,y) 坐标列表,我需要按 X 的顺序对它们进行排序

You can use a Bean Comparatoror a custom Comparator as described in the blog.

您可以使用Bean 比较器或博客中所述的自定义比较器。