This question already has answers here:
Explanation of “ClassCastException” in Java

(11个答案)


上个月关闭。





我的教授正在让我们实现Java可比较的接口,以帮助我的二进制搜索树比较包含被扫描单词的单词对象,然后将该单词与其他单词进行比较,但是由于某种原因,我正在做的第二个操作抛出了错误。我确实知道他给我们使用的方法确实在其中强制转换了(TreeComparable),但我仍然不是100%知道为什么这就是编译器冻结的行并给我错误

java.lang.ClassCastException: class ObjectTreeNode cannot be cast to class
TreeComparable (ObjectTreeNode and TreeComparable are in unnamed module of loader java.net.URLClassLoader


这就是导致它的方法

public void insertBSTDup(Object o) {
        ObjectTreeNode p, q;

        ObjectTreeNode r = new ObjectTreeNode(o);
        if (root == null)
            root = r;
        else {
            p = root;
            q = root;
            while (q != null && ((TreeComparable)(r.getInfo())).compareTo(p.getInfo()) != 0) { <---------
                p = q;
                if (((TreeComparable)(r.getInfo())).compareTo(p.getInfo()) < 0)
                    q = p.getLeft();
                else
                    q = p.getRight();
            }
            if (((TreeComparable)(r.getInfo())).compareTo(p.getInfo()) < 0)
                setLeftChild(p, r);
            else if (((TreeComparable)(r.getInfo())).compareTo(p.getInfo()) > 0)
                setRightChild(p, r);
            else ((TreeComparable)(p.getInfo())).operate(r.getInfo());
        }
    }


到目前为止,我的Word类是这样,底部是compareTo方法,其实现方式与我在第一次分配中所做的第一个compareTo相似,并且它正在比较字串,以便知道将其添加到何处。

public class Word implements TreeComparable
{
    private String word;
    private ObjectList list = new ObjectList();
    private ObjectListNode obj;
    private int numberOfTimes = 1, LineNumber, position;


    public Word(String word, int LineNumber, int position)
    {
        this.word = word;
        this.LineNumber = LineNumber;
        this.position = position;
    }

    public int compareTo(Object o)
    {
        Word w = (Word) o;
        return word.compareTo(w.getWord());
    }

    public String getWord()
    {
        return word;
    }


这是treeComparable方法

public interface TreeComparable
{
    public int compareTo(Object O);
    public void operate(Object O);
    public void visit();
}



除了删除treeComparable强制转换之外,我还需要做些什么改变以使错误消失,而我必须继续执行该项目

另外,这是Word对象将要进入的objectTreeNode对象

public class ObjectTreeNode implements ObjectTreeNodeInterface
{
    private Object info;
    private ObjectTreeNode left;
    private ObjectTreeNode right;

    public ObjectTreeNode() {
        info = null;
        left = null;
        right = null;
    }

    public ObjectTreeNode (Object o) {
        info = o;
        left = null;
        right = null;
    }

    public void setInfo(Object o) {
        info = o;
    }

    public Object getInfo() {
        return info;
    }

    public void setLeft(ObjectTreeNode p) {
        left = p;
    }

    public ObjectTreeNode getLeft() {
        return left;
    }

    public void setRight(ObjectTreeNode p) {
        right = p;
    }

    public ObjectTreeNode getRight() {
        return right;
    }
}


这是主要的

public static void main(String args[]) throws IOException
    {
        Hash h = new Hash();
        Word w;
        ObjectBinaryTree bt = new ObjectBinaryTree();
        ObjectTreeNode node;
        Scanner in = new Scanner(new File("getty.txt"));
        PrintWriter pw = new PrintWriter(new FileWriter("csis.txt"));
        int numberOfLines = 1;
        //h.check();


        while(in.hasNext())
        {
            String word = in.nextLine();
            String[] ar = word.split(" ", 0);

            System.out.print("\n" + (numberOfLines++) + ": ");
            int i = 0;
            while(i < ar.length)
            {
                char check = ar[i].charAt(ar[i].length() - 1);
                if(check == ',' || check == '.' || check == '!' || check == '?')
                {
                    ar[i] = ar[i].substring(0, ar[i].length() - 1);
                }
                w = new Word(ar[i], numberOfLines, (i + 1));
                node = new ObjectTreeNode(w);
                //System.out.println(ar[i]);
                bt.insertBSTDup(node);
                System.out.print("(" + (i + 1) + ") " + ar[i] + " ");
                i++;
            }
        }
    }

最佳答案

您的insertBSTDup方法期望getInfo的每个返回值都是TreeCompareable类型。它还接受object作为输入参数,这大概是要插入的对象,因此也应该是TreeCompareable。实际上,您可以立即将其包装在ObjectTreeNode中:

public void insertBSTDup(Object o) {
        ObjectTreeNode p, q;

        ObjectTreeNode r = new ObjectTreeNode(o);


但是,当您调用insertBSTDup时,您不会传递Word对象(该对象将实现TreeComparable,而是实现ObjectTreeNode

            node = new ObjectTreeNode(w);
            bt.insertBSTDup(node);


因此,可以将insertBSTDup的参数更改为ObjectTreeNode并避免再次包装它,或者将w传递给insertBSTDup而不是Node

从更一般的意义上讲,如果您真的希望Object时不只是将TreeComparable作为参数,则可以避免很多情况。这样,编译器会告诉您ObjectTreeNode不是TreeComparable而不是仅在运行时发生的问题。

基本上,每个使用Object的地方都应该改为TreeComparable。实际上,如果您已经学过它们,则应该改用泛型。

08-28 18:17