[英]java.lang.ClassCastException: com.MyComp.model.Image cannot be cast to java.lang.Comparable
I try to sort a List with the following code: 我尝试使用以下代码对列表进行排序:
List<Image> sortedImages = new LinkedList<Image>(inputImages);
Collections.sort(sortedImages, imageScoreComparator);
and 和
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));
}
}
}
But I get this error: 但是我得到这个错误:
java.lang.ClassCastException: com.MyComp.model.Image cannot be cast to java.lang.Comparable
This is how I init imageScoreComparator
这就是我初始化imageScoreComparator
imageScoreComparator = mock(ImageScoreComparator.class);
when(imageScoreComparator.compare(image1, image2)).thenReturn(0);
It sounds like your imageScoreComparator
variable is null. 听起来您的imageScoreComparator
变量为null。 If the Comparator
passed as the second parameter to Collections.sort
is null, it does not treat that as an error; 如果作为第二个参数传递给Collections.sort
的Comparator
为null,则不会将其视为错误; rather it will try to cast each item in the list to Comparable
, sorting them according to their natural sort order, which won't work for these objects. 相反,它将尝试将列表中的每个项目Comparable
为Comparable
,并根据其自然排序顺序对其进行排序,这不适用于这些对象。
Make sure you're initializing the imageScoreComparator
variable to something non-null. 确保将imageScoreComparator
变量初始化为非空值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.