0

我试图以两种不同的方式对arrayList 进行排序,一种是通过arrayList 中对象的区域,另一种是通过arrayList 中对象的名称(shape1,shape2)。当我将对象打印到文件中时,它们看起来像这样: shape1: (points, radius, etc...) 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()
4

4 回答 4

3

解决方案 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());
于 2012-04-24T03:50:49.423 回答
1

看一下Comparator类和Collections.sort(List<T>, Comparator<? super T>)方法。

于 2012-04-24T03:40:44.397 回答
1

由于这是作业,我不会发布任何代码。

如果您不允许使用Arrays.sort,您可以实现选择排序- 它非常简单,并且您已经在代码中编写了它的开头部分。这个想法是在外循环的每次迭代中i选择从ishapes.size()使用内循环 on的段中的最小元素j,并将该元素放置在i数组的第 -th 位置。您的内部循环应如下所示:

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

现在根据您的情况,您可以将-th 元素与-thif交换,或者将其保持在原位并继续前进。ji

要对字符串进行排序,请在您的条件下使用compareTo方法。if

于 2012-04-24T03:43:49.390 回答
0

我认为你应该使用这样的东西:

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

了解更多信息

于 2012-04-24T03:59:15.183 回答