0

我想使用 Collections.sort() 方法对包含“计数器”对象的数组列表进行排序。我已经在 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);
    }
}

下面的方法是我调用排序方法的地方。

    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;
}
4

1 回答 1

3

为我工作,(OpenJDK7)>

// 主要的 - - - - - - - - - - - - - - - - - - - - - - - - -----

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);
   }
}

// 柜台 - - - - - - - - - - - - - - - - - - - - - - - - --

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 + '}';
    }
}

输出>

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

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

于 2013-10-16T14:07:46.207 回答