使用Comparable接口时的类强制转换异常

时间:2014-03-03 18:46:20

标签: java classcastexception comparable

当我尝试执行下面的代码时,编译器在第13行抛出错误为“java.lang.ClassCastException”。有人能让我知道下面代码有什么问题吗?

package chapter11;

import java.util.*;

public class ComparableExample {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Item[] items = new Item[3];
        items[0] = new Item(102, "Duct Tape");
        items[1] = new Item(103, "Bailing Wire");
        items[2] = new Item(104, "Chewing Gum");

        Arrays.sort(items);
        for (Item i : items) {
            System.out.println(i.getNumber() + ":" + i.getDescription());
        }
    }
}

interface Comparable {
    int compareTo(Object o);
}

class Item implements Comparable {
    private int number;
    private String description;

    public Item(int number, String description) {
        this.number = number;
        this.description = description;
    }

    public int getNumber() {
        return number;
    }

    public String getDescription() {
        return description;
    }

    public int compareTo(Object o) {
        Item i = (Item) o;
        if (this.getNumber() < i.getNumber())
            return -1;
        if (this.getNumber() < i.getNumber())
            return 1;
        return 0;
    }
}

感谢任何帮助, 谢谢!

1 个答案:

答案 0 :(得分:2)

删除Comparable界面,然后使用Comparable interface from the Java api. 而且,也许你可以改变

public int compareTo(Object o) {
        Item i = (Item) o;
        if (this.getNumber() < i.getNumber())
            return -1;
        if (this.getNumber() < i.getNumber())
            return 1;
        return 0;
    }

进入:

public int compareTo(Object o) {
            Item i = (Item) o;
            if (this.getNumber() < i.getNumber())
                return -1;
            if (this.getNumber() > i.getNumber())
                return 1;
            return 0;
        }