比较器类用法

时间:2013-04-06 20:59:09

标签: java sorting arraylist compare comparator

我正在尝试让这个程序进行编译,并且现在已经停留了好几个小时。我正在尝试对包含矩形的ArrayLists进行排序。我试图通过上升宽度,下降宽度和宽度相同的高度对这些矩形进行排序。我有一个包含main方法和ArrayLists内容的类,还有一个DescendingComparator类和一个AscendingComparator类,但不能让它们在main方法中运行。这是我的代码。任何建议都有帮助,谢谢。

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

}

1 个答案:

答案 0 :(得分:0)

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