簡體   English   中英

如何在Java中按對象的組件對arrayList進行排序

[英]How to sort an arrayList of objects by their components in java

我試圖以兩種不同的方式對arrayList進行排序,一種通過arrayList內對象的區域,另一種通過arrayList中對象的名稱(shape1,shape2)進行排序。 當我將它們打印到文件中時,這些對象看起來像這樣:shape1 :(點,半徑等)area = 0.0,並且形狀保持不變。 我嘗試查看其他類似的問題,但全部使用Collections.sort回答。 我不確定我應該使用這種方法。 這是我正在與您合作的一些代碼:

for (int i =0; i <shapes.size();i++){
    for (int j = 1; j<shapes.size(); j++){
        if (shapes.get(i).getShape().area() > shapes.get(j).getShape().area())
        {
            //
        }
        else
        {
            //
        }
    }
}

我不確定該怎么做。 有指針嗎? 對於按名稱排序,我必須使用:

shapes.get(i).getName()

解決方案1

您的對象可以實現Comparable接口,並使用Collections.sort(List list)進行排序。

public class Shape implements Comparable<Shape> {
    @Override
    public int compareTo(Shape o) {
        if(o == null) {
            return 1;
        }
        if(getName() == null || o.getName() == null) {
            return 0;
        } else if(getName() != null && o.getName() == null) {
            return 1;
        } else if(getName() == null && o.getName() != null) {
            return -1;
        }
        return getName().compareTo(o.getName());
    }
}

Collections.sort(shapes);

解決方案2

創建一個實現Comparator並使用Collections.sort(List list,Comparator c)的類

public class ShapeComparator implements Comparator<Shape> {
    @Override
    public int compare(Shape s1, Shape s2) {
        if(s1 == null || s2 == null) {
            return 0;
        } else {
            return s1.getName().compareTo(s2.getName());
        }
    }
}

Collections.sort(shapes, new ShapeComparator());

由於這是家庭作業,因此我不會發布任何代碼。

如果不允許使用Arrays.sort ,則可以實現Selection Sort-這非常簡單,並且已經在代碼中寫了它的開頭。 這個想法是在i上的外循環的每次迭代中,使用j上的內循環從ishapes.size()的段中選擇最小的元素,並將該元素放置在數組的第i個位置。 您的內部循環應如下所示:

for(int j = i+1 ; j<shapes.size(); j++)
//          ^--- this is what's changed

現在,根據您的if條件,您可以將j -th元素與i -th交換,或將其保留在適當位置並繼續前進。

要對字符串進行排序,請在if條件中使用compareTo方法。

我認為你應該使用這樣的東西:

        Collections.sort(shapes, new Comparator<Object>() {
            public int compare(Object obj1, Object obj2) {
                Shape shape1 = ((Shape) obj1).getShape();
                Shape shape2 = ((Shape) obj2).getShape();

                String name1 = ((Shape) obj1).getName();
                String name2 = ((Shape) obj1).getName();

                Double area1 = shape1.area();
                Double area2 = shape2.area();

                int areaCmp = area1 - area2;
                if( areaCmp!= 0 ) {
                    return areaCmp;
                }

                return name1.compareTo(name2);
            }
        });

了解更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM