【发布时间】:2013-04-06 20:59:09
【问题描述】:
我正在尝试编译这个程序,但现在已经卡住了几个小时。我正在尝试对包含矩形的 ArrayLists 进行排序。当宽度相同时,我试图按宽度递增、宽度递减和高度对这些矩形进行排序。我有一个包含主方法和 ArrayLists 内容的类,还有一个 DescendingComparator 类和一个 AscendingComparator 类,但无法让它们在主方法中运行。这是我的代码。任何建议都有帮助,谢谢。
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class SortingHomework10 extends Rectangle {
public static void main(String[] args){
//set up first array list with rectangles of differing widths
ArrayList<Rectangle> first = new ArrayList<Rectangle>();
Rectangle rectangleOne = new Rectangle(2,6);
Rectangle rectangleTwo = new Rectangle(4,4);
Rectangle rectangleThree = new Rectangle(2,5);
first.add(rectangleOne);
first.add(rectangleTwo);
first.add(rectangleThree);
//set up second array list with rectangles that have same width
ArrayList<Rectangle> second = new ArrayList<Rectangle>();
Rectangle rectangleFour = new Rectangle(2,5);
Rectangle rectangleFive = new Rectangle(2,4);
Rectangle rectangleSix = new Rectangle(2,3);
Rectangle rectangleSeven = new Rectangle(1,3);
second.add(rectangleFour);
second.add(rectangleFive);
second.add(rectangleSix);
second.add(rectangleSeven);
System.out.println("Before sorting.");
System.out.println(first);
System.out.println("");
//Sorting in ascending width
Collections.sort(first, new AscendingComparator());
System.out.println("In ascending order by width.");
for(int j=0; j <first.size(); j++){
System.out.println(first.get(j));
}
System.out.println("");
System.out.println("In descending order by width.");
//Sorting in descending width
//for(int i = first.size() - 1; i >=0; i--){
//System.out.println(first.get(i));
Collections.sort(first, new DescendingComparator());
}
}
//////////AscendingComparator Class code
public class AscendingComparator implements Comparator<Rectangle> {
@Override
public int compare(Rectangle o1, Rectangle o2) {
if(o1.getWidth() < o2.getWidth()){
return -1;
}
if(o1.getWidth() > o2.getWidth()){
return 1;
}
else return 0;
}
}
//////////////DescendingComparator Class code
public class DescendingComparator implements Comparator<Rectangle> {
@Override
public int compare(Rectangle o1, Rectangle o2) {
if(o1.getWidth() > o2.getWidth()){
return -1;
}
if(o1.getWidth() < o2.getWidth()){
return 1;
}
else return 0;
}
}
【问题讨论】:
-
那会发生什么?
-
如果所有代码都在一个类中,它将无法编译。每个 Java 文件只允许一个公共顶级类。
-
不是,AscendingComparator 和 DescendingComparator 本身就是独立的类。它一直编译到 DescendingComparator 类。我是否在 main 方法中错误地使用了它们?
-
那么实际的错误是什么?
-
我终于弄明白了。不过谢谢。
标签: java sorting arraylist compare comparator