-1

我正试图让这个程序编译,现在已经卡在这个点上几个小时了。我正在尝试对包含矩形的 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;
    }

}
4

1 回答 1

0

看起来您对第一个集合进行了两次排序,而在构建第二个集合之后没有对它做任何事情。

于 2013-04-06T21:02:31.927 回答