有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java比较器类的使用

我正在试图编译这个程序,现在已经在这一点上被困了好几个小时了。我正在尝试对包含矩形的ArrayList进行排序。我试着按照上升宽度、下降宽度和宽度相同时的高度对这些矩形进行排序。我有一个包含main方法和ArrayLists内容的类,还有一个genderingcomparator类和一个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) 个答案

  1. # 1 楼答案

    看起来,你要对第一个集合进行两次排序,而在建立第二个集合之后,却什么都不做