java基础问题,求各位大神帮忙解答,感激不尽!
巴扎黑
巴扎黑 2017-04-17 17:27:08
0
3
726

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

}

巴扎黑
巴扎黑

reply all(3)
伊谢尔伦

直接让item实现Comparable接口

阿神
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.......
}
}
PHPzhong

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!