2010-11-16 5 views
0

J'utilise la classe point pour gérer une liste de (x, y) les coordonnées et j'ai besoin de les trier par ordre de X.Java comment trier un ArrayList d'objets Point

Je lis en ligne pour faire une nouvelle classe PointCompare qui implémente Comparator, mais je ne suis pas sûr comment cela fonctionne et donc j'ai une erreur de compilation dans la méthode sortByXCoordinates.

L'aide serait grandement appréciée, et tous les commentaires sont les bienvenus, merci d'avance. Voici une partie de mon 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(); 


} 
} 

Répondre

4

Vous étiez proche. Le problème que vous aviez était tout simplement que vous invoquez

public void sortByXCoordinates(){ 

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

    } 

Ce que vous voulez est le suivant:

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

    } 
} 
0

J'utilise la classe point pour gérer une liste de (x, y) les coordonnées et je dois les trier afin de X

Vous pouvez utiliser un Bean Comparator ou un comparateur personnalisé comme décrit dans le blog.

+0

Merci beaucoup. Cela m'évite d'écrire un tri à bulles pour les trier manuellement! – user492837

+0

> Utilisation du tri à bulles. Pas même une fois. – easymoden00b

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

je vais ignorer tout le code affiché parce que vous avez juste largué tout sans prendre le temps identifier les zones pertinentes.

maintenant, à partir de votre question: vous avez un ArrayList contenant Point s. Vous voulez le trier par l'axe X/valeur.

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

Premièrement, vous devez un Comparator qui comparera l'un à l'autre Point. Je choisis de "boxer" l'int à un nombre entier et d'utiliser la méthode compareTo d'Integer. Vous pourriez proposer une méthode de comparaison plus ordonnée, à vous.

Ensuite, vous pouvez utiliser la méthode utilitaire Collections.sort

Collections.sort(list, comp); 

et votre liste est triée.

+0

lol j'ai eu une downvote pour ça ... – pstanton