2010-11-16 12 views
0

Я использую класс точек для управления списком (х, у) координаты, и мне нужно, чтобы отсортировать их в порядке X.Java, как сортировать ArrayList точечных объектов

я прочитал в Интернете, чтобы сделать новый класс PointCompare, который реализует Comparator, однако я не уверен, как это работает, и поэтому у меня есть ошибка компилятора в методе 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(); 


} 
} 

ответ

4

Вы были близки. Проблема у вас просто, что вы вызвали

public void sortByXCoordinates(){ 

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

    } 

Что вы хотите, это:

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

Я использую класс точек для управления списком (х, у) координаты, и мне нужно, чтобы отсортировать их в порядке X

Вы можете использовать Bean Comparator или пользовательский Компаратор, как описано в блоге.

+0

Большое спасибо. Это спасает меня от написания пузырьковой сортировки, чтобы разобраться с ними вручную! – user492837

+0

> используя пузырь вид. Даже не один раз. – 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

я буду игнорировать все код, который вы публикуемую, потому что вы только что бросили все, не тратя время для определения соответствующих областей.

сейчас, с вашего вопроса: у вас есть ArrayList, содержащий Point s. Вы хотите отсортировать его по оси X/значению.

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

Во-первых, вам нужно Comparator, который сравнивает один Point к другому.

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

Я выбираю «поле» int целочисленному и использует метод compareTo Integer. Вы можете придумать более аккуратный метод сравнения, вплоть до вас.

Затем вы можете использовать метод полезности Collections.sort

Collections.sort(list, comp); 

и список сортируется.

+0

lol Я получил нижний план для этого ... – pstanton

Смежные вопросы