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

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

}

巴扎黑
巴扎黑

모든 응답(3)
伊谢尔伦

항목이 Comparable 인터페이스를 직접 구현하도록 합니다

阿神

으아악

PHPzhong

이 예외는 유형 변환 예외입니다.
SortedSet<Item> sortedByDes = new TreeSet<>(new Comparator<Item>() {…}
다형성은 상위 클래스 객체로 변환된 하위 클래스 객체여야 합니다. , 새 Comparator은 Comparable의 하위 클래스이고 작성한 Item {...} 클래스는 Comparable의 하위 클래스가 아니므로 유형 변환 오류가 발생합니다. 해결 방법은 Item이 Comparable 인터페이스를 구현하도록 하는 것입니다. 🎜>.

최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿