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

0 java sorting arraylist comparator

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

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

非常感谢帮助,欢迎任何评论,提前感谢.这是我的一些代码:

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();


 }
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*kin 6

private ArrayList<Point> coordinateList = new ArrayList<Point>();
Run Code Online (Sandbox Code Playgroud)

...

Collections.sort(coordinateList, new PointCompare());
Run Code Online (Sandbox Code Playgroud)

...

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)