开发者

Java how to sort an ArrayList of Point objects

开发者 https://www.devze.com 2023-01-25 05:03 出处:网络
I\'m using the Point Class to manage a list of (x,y) coordinates and I need to sort them in order of X.

I'm using the Point Class to manage a list of (x,y) coordinates and I need to sort them in order of 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.

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


 }
}


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;
        }
    }
}


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

    }
}


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 ArrayList containing Points. You want to sort it by the X axis/value.

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

Firstly you need a Comparator which will compare one Point to another.

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.

Then you can use the utility method Collections.sort

Collections.sort(list, comp);

and your list is sorted.


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

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号