我尝试使用以下代码对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);
答案 0 :(得分:4)
听起来你的imageScoreComparator
变量为空。如果作为Comparator
的第二个参数传递的Collections.sort
为空,则不会将其视为错误;相反,它会尝试将列表中的每个项目转换为Comparable
,根据它们的自然排序顺序对它们进行排序,这对于这些对象不起作用。
确保您将imageScoreComparator
变量初始化为非空值。