Maison > Questions et réponses > le corps du texte
程序运行返回Exception in thread "main" java.lang.ClassCastException: Item cannot be cast to java.lang.Comparable.
求各位大哥大叔帮看看哪里出了问题。。。。
public class LinkListTest {
public static void main(String[] args) {
SortedSet<Item> oo = new TreeSet<>();
oo.add(new Item("afang", 1011));
oo.add(new Item("fangjie", 1222));
oo.add(new Item("fangfang", 889));
System.out.println(oo);
SortedSet<Item> sortedByDes = new TreeSet<>(new
Comparator<Item>() {
public int compare(Item a, Item b) {
String desA = a.getDescription();
String desB = b.getDescription();
return desA.compareTo(desB);
}
});
sortedByDes.addAll(oo);
System.out.println(sortedByDes);
}
}
class Item {
private String description;
private int id;
public Item(String aDes, int aId) {
description = aDes;
id = aId;
}
public String getDescription() {
return description;
}
}
阿神2017-04-17 17:29:08
class Item implements Comparable<Item> {
private String description;
private int id;
public Item(String aDes, int aId) {
description = aDes;
id = aId;
}
public String getDescription() {
return description;
}
public int compareTo(Item o) {
//dosomething.......
}
}
PHPz2017-04-17 17:29:08
这个异常是类型转换异常
SortedSet<Item> sortedByDes = new TreeSet<>(new Comparator<Item>() {…}
多态必须是子类对象转换为父类对象,new Comparator<Item>是Comparable的子类,而你写的class Item {…}并不是Comparable的子类,所以会出现类型转换错误。解决办法就是让你的Item 实现Comparable接口