首页  >  问答  >  正文

java基础问题,求各位大神帮忙解答,感激不尽!

程序运行返回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;
    }

}

巴扎黑巴扎黑2713 天前736

全部回复(3)我来回复

  • 伊谢尔伦

    伊谢尔伦2017-04-17 17:29:08

    直接让item实现Comparable接口

    回复
    0
  • 阿神

    阿神2017-04-17 17:29:08

    雷雷

    回复
    0
  • PHPz

    PHPz2017-04-17 17:29:08

    这个异常是类型转换异常
    SortedSet<Item> sortedByDes = new TreeSet<>(new Comparator<Item>() {…}
    多态必须是子类对象转换为父类对象,new Comparator<Item>是Comparable的子类,而你写的class Item {…}并不是Comparable的子类,所以会出现类型转换错误。解决办法就是让你的Item 实现Comparable接口

    回复
    0
  • 取消回复