Home  >  Q&A  >  body text

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 days ago738

reply all(3)I'll reply

  • 伊谢尔伦

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

    Directly let the item implement the Comparable interface

    reply
    0
  • 阿神

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

    reply
    0
  • PHPz

    PHPz2017-04-17 17:29:08

    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#🎜🎜. #

    reply
    0
  • Cancelreply