Java - Collection.Sort over Interface Objects

MrB*_*MrB 5 java sorting generics comparable

我有一些抽象类,每个类都超级分为三个或四个具体的类和形式:

public abstract class TypeOfMapObject extends IrrelevantClass implements Serializable, MapObject, Comparable<MapObject>
{
  //irrelevant stuff
  @Override
  public int compareTo(MapObject m)
  {
    //specific algorithm for natural ordering
  }
}
Run Code Online (Sandbox Code Playgroud)

其他地方在我的代码我有一个ArrayList<MapObject>(其被正确填充,我已经检查了)叫tempMapObjectsArray 我希望那种ArrayList使用Collections.sort(tempMapObjectsArray)(或者更确切地说,我想那种ArrayList,似乎Collections.sort()是做到这一点的最好办法,具体办法它排序并不重要).

它没有编译和给出消息(在Netbeans中):

no suitable method found for sort(java.util.ArrayList<Model.MapObject>)
 method java.util.Collections.<T>sort(java.util.List<T>,java.util.Comparator<? super T>) is not applicable
 (cannot instantiate from arguments because actual and formal argument lists differ in length)
 method java.util.Collections.<T>sort(java.util.List<T>) is not applicable
  (inferred type does not conform to declared bound(s)
   inferred: Model.MapObject
   bound(s): java.lang.Comparable<? super Model.MapObject>)
Run Code Online (Sandbox Code Playgroud)

似乎我在TypeOfMapObject课堂上定义了一般错误,但这是我第一次真正使用泛型并且它已经达到了我或多或少随意尝试的阶段.我正在阅读教程,但到目前为止它根本就没有"点击"我做错了什么.

编辑:每个不同的抽象类的子类必须相互媲美-所以,如果我有抽象类TypeofMapObject1,TypeOfMapObject2等等,然后我需要能够到为1的子类比较2的子类.

Boh*_*ian 10

将Comparable类型与类匹配:

public abstract class TypeOfMapObject extends IrrelevantClass implements Serializable, MapObject, Comparable<TypeOfMapObject> {
    @Override
    public int compareTo(TypeOfMapObject m)
    {
        //specific algorithm for natural ordering
    }
}
Run Code Online (Sandbox Code Playgroud)

或者只是不在抽象类中定义compareTo方法 - 留下它来实现子类.


要解决编辑问题:

如果要比较不同的子类型,请让它们实现一个返回值(比如String)的方法,以便与它们进行比较.例如:

public abstract class TypeOfMapObject extends IrrelevantClass implements Serializable, MapObject, Comparable<TypeOfMapObject> {
    @Override
    public int compareTo(TypeOfMapObject m)
    {
        return compareValue().compareTo(m.compareValue());
    }

    // subclasses to return their value to compare
    protected abstract String compareValue();
}
Run Code Online (Sandbox Code Playgroud)

从中返回的类型compareValue()可以是任何可比较的类型,例如Integer,Date等等.