繁体   English   中英

Java - Collection.Sort over Interface Objects

[英]Java - Collection.Sort over Interface Objects

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

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

在我的代码的其他地方,我有一个名为tempMapObjectsArrayArrayList<MapObject> (正在正确填充,我已经检查过)我想使用Collections.sort(tempMapObjectsArray)对该ArrayList进行排序(或者,我想要对该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>)

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

编辑:各种抽象类的每个子类需要相互比较 - 所以如果我有抽象类TypeofMapObject1TypeOfMapObject2等,那么我需要能够将1的子类与2的子类进行比较。

将Comparable类型与类匹配:

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

或者只是不在抽象类中定义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();
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM