即使实现了类比,也无法将类强制转换为java.lang.Comparable

时间:2013-10-16 13:51:50

标签: java sorting arraylist comparable

我想使用Collections.sort()方法对包含“Counter”对象的arraylist进行排序。我在Counter类中实现了类似的接口。我仍然得到一个阶级演员例外。我已经发布了以下代码。

public class Counter implements Comparable<Counter>, java.io.Serializable {

    private String description;

    public Counter() {
    }

    public Counter(String description) {

        this.description = description;

    }

    public int compareTo(Counter other) {
        return description.compareTo(other.description);
    }
}

以下方法是我调用sort方法的地方。

    protected List < Counter > prepareCounters(final Integer authorityID) throws ServiceException {
    if (authorityID == null) {
        return new ArrayList < Counter >();
    }

    List < Counter > countersInRegistry = new ArrayList < Counter >(counterRegistry.getAllCounters());
    List < Counter > countersFromService =
            new ArrayList < Counter >(counterService.searchCounters(authorityID, null, null));
    countersFromService.removeAll(countersInRegistry);
    Collections.sort(countersFromService);
    return countersFromService;
}

1 个答案:

答案 0 :(得分:3)

为我工作,(OpenJDK7)&gt;

// Main -------------------------------------------- --------

package stackover_basic;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class StackOver_basic {
    public static void main(String[] args) {
        List<Counter> asList = Arrays.asList(new Counter("xx"), new Counter("aa"), new Counter("zz"));
        System.out.println("before" + asList);
        Collections.sort(asList);        
        System.out.println("after" + asList);
   }
}

// Counter -------------------------------------------- -----

public class Counter implements Comparable<Counter>, java.io.Serializable {

    private String description;

    public Counter() {
    }

    public Counter(String description) {
        this.description = description;
    }

    @Override
    public int compareTo(Counter other) {
        return description.compareTo(other.description);
    }

    @Override
    public String toString() {
        return "Counter{" + "description=" + description + '}';
    }
}

输出&GT;

run:
before[Counter{description=xx}, Counter{description=aa}, Counter{description=zz}]
after[Counter{description=aa}, Counter{description=xx}, Counter{description=zz}]

编辑:classCastExc很可能来自你对compareTo的定义。原因是:您正在向集合中添加一个错误的对象,即方法counterService.searchCounterscounterRegistry.getAllCounters的返回类型在Counter类中不是通用的。