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

程序运行返回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)
伊谢尔伦

Directly let the item implement the Comparable interface

阿神
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

This exception is a type conversion exception
SortedSet<Item> sortedByDes = new TreeSet<>(new Comparator<Item>() {…}
Polymorphism must be a subclass object converted to a parent Class object, new Comparator<Item> is a subclass of Comparable, and the class Item {...} you wrote is not a subclass of Comparable, so a type conversion error will occur. The solution is to make your Item implement the Comparable interface#🎜🎜. #

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template