0

theTree.insert(new File("a", 1));我收到与:一致的错误The method insert(Comparable) in the type Tree is not applicable for the arguments (File)

当我尝试这样投射时,theTree.insert((Comparable) new File("a", 1));我得到其他错误: E xception in thread "main" java.lang.ClassCastException: File cannot be cast to java.lang.Comparable at TreeApp.main(tree.java:134)

为什么我不能通过这个对象?

我的对象:

class FileObject
{
    public String name;
    public int size;

    File(String a, int b)
    {
        this.name = a;
        this.size = b;
    }
}
4

2 回答 2

7

因为你的File类没有实现Comparable.

于 2012-11-06T08:02:47.880 回答
4

你需要实施Comparable<File>

class File implements Comparable<File>
    {
        public String name;
        public int size;

        File(String passedName, int passedSize)
        {
            this.name = passedName;
            this.size = passedSize;
        }

        @Override
        public int compareTo(File o) {
            //e.g Provide comparable on size
            return Integer.valueOf(size).compareTo(o.size);
        }
    }

参考:

注意:请compareTo在合同中提供实现equals方法。

于 2012-11-06T08:03:27.110 回答