无法正确排序我的arraylist

时间:2015-10-14 00:32:24

标签: java sorting object arraylist

所以我试图按升序(按区域)对几何对象的arraylist进行排序。但是,我遇到了错误

//Member[MemberName/BusinessNameLine1Txt='Mouser0']/FormA1

在我的代码块中

The method add(GeometricObject) in the type ArrayList<GeometricObject> is not applicable for the arguments (double)

线

private static void selectionSort(ArrayList<GeometricObject> list) {
        for (int i = 0; i < list.size(); i++) {
            if (i < list.size() - 1) {
                if (list.get(i).getArea() > list.get(i + 1).getArea()) {
                    double j = list.get(i).getArea();
                    list.remove(i);
                    list.add(i, list.get(i));
                    list.remove(i + 1);
                    list.add(j).getArea();
                    i = -1;
                }
            }
        }

     }

同样,我只是尝试按照它们的区域排序它们,以便我以后可以打印数组。任何有关正确方向的帮助或指示都将不胜感激,谢谢!

2 个答案:

答案 0 :(得分:1)

我想你想要这样做

private static void selectionSort(ArrayList<GeometricObject> list) {
        for (int i = 0; i < list.size(); i++) {
            if (i < list.size() - 1) {
                if (list.get(i).getArea() > list.get(i + 1).getArea()) {
                    GeometricObject j = list.get(i);
                    list.remove(i);
                    list.add(i, list.get(i));
                    list.remove(i + 1);
                    list.add(j);
                    i = -1;
                }
            }
        }

     }

我会考虑将j更改为更有意义的名称。出现此问题的原因是无法比拟的数据类型

答案 1 :(得分:0)

试试这个:

    Collections.sort(list, new Comparator<GeometricObject>() {
        @Override
        public int compare(GeometricObject o1, GeometricObject o2) {
            if (o1.getGmtModified() != null && o2.getGmtModified() != null){
                if(o1. getArea() < o2. getArea()) {
                    return 1;
                }else if(o1. getArea() > o2. getArea()){
                    return -1;
                }else{
                    return 0;                        
                }
            }
            return 0;
        }
    });