1

我设置了多个对象,都实现了同一个类。所有这些对象都有一个共同的方法,“getRatio”。我想根据“getRatio”方法的值按数字升序对这些对象进行排序,并且让对象按顺序调用它们的 toString 方法。我试图应用这个想法,但我只是订购数字本身。

    List shapeList = new ArrayList();
    shapeList.add(rectangle);
    shapeList.add(triangle_right);
    shapeList.add(isosceles);
    shapeList.add(triangle);
    shapeList.add(triangle2);
    shapeList.add(triangle3);
    Collections.sort(shapeList);
    for (Shape shape : shapeList) {
        System.out.println(shape.toString());
    }

没有找到适合 add(RightTriangle) shapeList.add(triangle_right) 的方法;

错误:找不到符号 Comparable.sort(shapeList);

4

3 回答 3

2

您可以为 Arrays.sort() 方法提供一个比较在您的情况下,它看起来像这样(我假设该方法在一个公共类/接口中):getRatioShape

public class ShapeComparator implements Comparator<Shape> { 
    int compareTo (final Shape shape1, final Shape shape2) {
        return (int) Math.signum (shape1.getRatio () - shape2.getRatio ());
    }
}

您还可以使您的公共类实现Comparable接口,如下所示:

public class Shape implements Comparable<Shape> {
    int compareTo (final Shape other) {
        return (int) Math.signum (getRatio () - other.getRatio ());
    }
}
于 2012-11-20T00:40:07.717 回答
1

扩展其他答案,您可以Comparator按如下方式定义和排序数组:

Arrays.sort(myArray, new Comparator<MyClass>() {
    @Override
    public int compare(MyClass c1, MyClass c2) {
        return (new Double(c1.getRatio())).compareTo(c2.getRatio());
    }
});

如果您计划像这样对多个数组进行排序,那么MyClass实现Comparable接口是明智的。


编辑List:要对s(例如进行排序ArrayList您可以使用类似的概念,但使用Collections.sort

Collections.sort(shapeList, new Comparator<MyClass>() {
    @Override
    public int compare(MyClass c1, MyClass c2) {
        return (new Double(c1.getRatio())).compareTo(c2.getRatio());
    }
});

相关文件:

于 2012-11-20T00:44:04.097 回答
0

你应该让你的 Object 实现Comparable

更多信息在这里

您需要实现compareTo()以便比较两个对象的比率。

您可以这样做:

class Foo implements Comparable<Foo> {

    private double ratio;

    public double getRatio() {
        return ratio;
    }

    public int compareTo(Foo otherFoo) {
        if (otherFoo == null) {
            return -1;
        }
        return ratio - otherFoo.ratio;
    }

}

以下是对 Foo 对象的集合进行排序的方法:

List<Foo> fooList = createFooList();
Collections.sort(fooList);

// print the Foos in order

for (Foo f : fooList) {
    System.out.println(f.toString());
}
于 2012-11-20T00:40:50.483 回答