java.lang.ClassCastException:com.MyComp.model.Image无法强制转换为java.lang.Comparable

时间:2014-08-17 11:43:22

标签: java sorting collections guava

我尝试使用以下代码对List进行排序:

        List<Image> sortedImages = new LinkedList<Image>(inputImages);
        Collections.sort(sortedImages, imageScoreComparator);

class ImageScoreComparator implements Comparator<Image> {

    ImageScoreCalculator imageScoreCalculator;

    ImageScoreComparator() {
        this(new ImageScoreCalculator(Calendar.getInstance()));
    }

    @VisibleForTesting
    ImageScoreComparator(ImageScoreCalculator imageScoreCalculator) {
        this.imageScoreCalculator = imageScoreCalculator;
    }

    @Override
    public int compare(Image image1, Image image2) {
        if (image2.isPromoted() && !image1.isPromoted()) {
            return 1;
        } else if (image1.isPromoted() && !image2.isPromoted()) {
            return -1;
        } else {
            return Double.compare(imageScoreCalculator.getScoreForImage(image1), imageScoreCalculator.getScoreForImage(image2));
        }
    }
}

但是我收到了这个错误:

java.lang.ClassCastException: com.MyComp.model.Image cannot be cast to java.lang.Comparable

这就是我初始化imageScoreComparator

的方式
imageScoreComparator = mock(ImageScoreComparator.class);
        when(imageScoreComparator.compare(image1, image2)).thenReturn(0);

1 个答案:

答案 0 :(得分:4)

听起来你的imageScoreComparator变量为空。如果作为Comparator的第二个参数传递的Collections.sort为空,则不会将其视为错误;相反,它会尝试将列表中的每个项目转换为Comparable,根据它们的自然排序顺序对它们进行排序,这对于这些对象不起作用。

确保您将imageScoreComparator变量初始化为非空值。