Java gewusst wie: Sortieren einer ArrayList von Point Objekte

Ich bin mit dem Punkt Klasse zur Verwaltung einer Liste von (x,y) - Koordinaten, und ich brauche, um Sie zu Sortieren, in der Reihenfolge des X.

Lese ich online, um eine neue Klasse PointCompare, die Comparator implementiert, aber ich bin mir nicht sicher, wie dies funktioniert und deshalb habe ich einen compiler-Fehler in der sortByXCoordinates Methode.

Hilfe würde geschätzt, eine Menge, und jegliche Kommentare sind willkommen, danke im Voraus.
Hier ist mein 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();


 }
}
InformationsquelleAutor user492837 | 2010-11-16
Schreibe einen Kommentar