对ArrayList <myinterface>进行排序

时间:2017-12-07 17:55:16

标签: java sorting arraylist interface compiler-errors

为了渲染顺序,我试图用每个对象中两个整数的总和对ArrayList<MyInterface>进行排序。此ArrayList中的对象实现相同的接口,但没有共同的母类。

class A implements MyInterface, Comparable<MyInterface> {

    @Override
    public int compareTo(MyInterface object1) {
        return (this.x+this.y)-(object1.getX()+object1.getY()); // Sort in ascending order
    }

    @Override
    public int getX() { return this.x; }

    @Override
    public int getY() { return this.y; }
    }

}

class B implements MyInterface, Comparable<MyInterface> {
    //Same than A, but A & B have no common motherclass.
}


interface MyInterface {

    int getX();
    int getY();
    int compareTo(MyInterface mi);

    ... //Other method that are the first reason I created the interface before.

}

然后我尝试像这样对我的arraylist进行排序:

ArrayList<MyInterface> myArrayList = new ArrayList<MyInterface>();
myArrayList.add(new A(1,2));
myArrayList.add(new A(5,6));
myArrayList.add(new B(3,1));
Collections.sort(gameRenderables); //I get the compile error here.

我收到错误:

Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for the arguments (ArrayList<Renderable>). The inferred type Renderable is not a valid substitute for the bounded parameter <T extends Comparable<? super T>>.

也许我正试图让一些事情变得不可能。如果是这种情况,你可以给我这个排序问题的替代解决方案吗?

1 个答案:

答案 0 :(得分:4)

您已将该类定义为实施Comparable,而不是将接口定义为扩展Comparable。如果不这样做,Java编译器就无法知道MyInterface的每个可能的实现实际上都是Comparable。接口具有与实现compareTo(MyInterface)的类的方法匹配的Comparable<MyInterface>方法的事实是无关紧要的。

简而言之:

interface MyInterface extends Comparable<MyInterface> {
    int getX();
    int getY();

    // No need for a compareTo method - we get it from the Comparable interface
}

class A implements MyInterface {
    // No changes required to your implementation
}