如何使用Comparable Interface比较ArrayList中对象的多个属性? [重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我需要通过相应的属性对我的ArrayList Rectangle中的list1对象进行排序:heightwidthtopCorner(Point)。我可以在评估一个属性时对列表进行排序。

我如何设置我的compareTo方法,以便它首先尝试通过height,然后通过width(如果所有对象高度相等)对列表中的对象进行排序,最后通过topCorner(如果所有对象高度和宽度相等)?

public class Point implements Comparable<Point> {

private int x;
private int y;

public Point(){
    this(0,0);
}
public Point(int x,int y){
    this.x=x;
    this.y=y;
}
public int getX(){
    return x;
}
public int getY(){
    return y;
}
public int compareTo(Point pt){
    if(x==pt.x){
        return y-pt.y;
    }
    else{
        return x-pt.x;
    }
}
public String toString(){
    return "("+x+", "+y+")";
}
}
class Rectangle implements Comparable<Rectangle> {

private int height;
private int width;
private Point topCorner;

public Rectangle(int x,int y,int height,int width){
    this.height=height;
    this.width=width;
    this.topCorner=new Point(x,y);
}
public int getHeight(){
    return height;
}
public int getWidth(){
    return width;
}
public Point getPoint(){
    return topCorner;
}
public int compareTo(Rectangle rect){
    if(height!=rect.height){
        int compareHeight=((Rectangle)rect).getHeight();
        return this.height-compareHeight;
    }
    else if(width!=rect.width){
        int compareWidth=((Rectangle)rect).getWidth();
        return this.width-compareWidth;
    }
    else if(topCorner!=rect.topCorner){
        Point comparePoint=((Rectangle)rect).getPoint();
        return this.topCorner-topCorner;
    }
    else{
        System.out.println("// ERROR BRO // ERROR BRO //");
    }
    return 0;
}
public String toString(){
    return "(H:"+height+", W:"+width+", P:"+topCorner+")";
}
}

===========================================================================

public class RectangleComparable {
public static void main(String[]args){
    Random rn=new Random(21);
    ArrayList<Rectangle> list1=new ArrayList<>();
    for(int index=0;index<10;index++){
        int ran1=rn.nextInt(21), ran2=rn.nextInt(21),
                ran3=rn.nextInt(21), ran4=rn.nextInt(21);
        list1.add((new Rectangle(5,ran2,ran3,ran4)));
    }
    System.out.println("KEY : H=height, W=width, P=point\n");
    System.out.println("Unsorted List : \n"+list1+"\n");
    Collections.sort(list1);
    System.out.println("Sorted List : \n"+list1);
}
}

如果这是一个重复的问题,我会继续道歉并道歉。我环顾四周,但是我找不到任何给我一个直接答案的东西(因为我还是一个编程菜鸟)。

java arraylist collections compareto
1个回答
1
投票

您可以编写自己的Comparator或构建如下:

Comparator
    .comparingInt(Rectangle::getHeight)
    .thenComparingInt(Rectangle::getWidth)
    .thenComparing(Rectangle::getTopCorner);
© www.soinside.com 2019 - 2024. All rights reserved.