【问题标题】:java.lang.ClassCastException: class [Ljava.lang.Object; cannot be cast to classjava.lang.ClassCastException: 类 [Ljava.lang.Object;不能被强制转换为类
【发布时间】:2020-06-28 05:53:32
【问题描述】:

我正在尝试在 Java 中实现 trie。当我测试我的方法“插入”是否有效时,出现以下错误。

Exception in thread "main" java.lang.ClassCastException: 
class [Ljava.lang.Object; cannot be cast to class [LTrie$TreeNode; ([Ljava.lang.Object; 
is in module java.base of loader 'bootstrap'; [LTrie$TreeNode; is in unnamed module of loader 'app')
at Trie.insert(Trie.java:36)
at Trie.main(Trie.java:47)

我也遇到了一些类似的问题,但仍然无法弄清楚。我想知道为什么我们不能将类型从 Object 转换为 TreeNode[] 数组。

我的代码如下。我知道按数组使用 dataIndexedCharMap 会浪费很多内存(HashTable 或 BST 会更好),但我只是想比较这三种方法的内存和效率但遇到了一些麻烦。

class Trie {
    private static final int R = 128;
    public TreeNode root;

    private static class TreeNode {
        private boolean isKey;
        private dataIndexedCharMap next;
        private TreeNode(boolean b, int R) {
            isKey = b;
            next = new dataIndexedCharMap<TreeNode>(R);
        }
    }

    public static class dataIndexedCharMap<V> {
        private V[] items;
        public dataIndexedCharMap(int R) {
            items = (V[]) new Object[R];
        }
    }

    /** Initialize your data structure here. */
    public Trie() {
        root = new TreeNode(false, R);
    }

    /** Inserts a word into the trie. */
    public void insert(String word) {
        TreeNode curr = root;
        for (int i = 0; i < word.length(); i++) {
            TreeNode[] array = (TreeNode[]) curr.next.items;
            array[word.charAt(i)] = new TreeNode(false, R);
            curr = array[word.charAt(i)];
            if (i == word.length() - 1) {
                curr.isKey = true;
            }
        }
    }

    public static void main(String[] args) {
        Trie obj = new Trie();
        obj.insert("apple");
    } 
}

【问题讨论】:

  • 你有没有试过这个私有dataIndexedCharMap next;
  • 您需要V 做什么?你不是一直想要new TreeNode[R] 吗?
  • @SabareeshMuralidharan 是的,但同样的问题会发生
  • @Thilo 我也试过了。当我用 TreeNode 替换 V 并且不使用强制转换时。 IntelliJ 告诉我不能直接实例化类型参数“TreeNode”。这就是我使用泛型类型的原因。
  • 顺便说一下,你应该遵循Java命名约定:变量名和方法名应该用camelCase写,类名用PascalCase。所以dataIndexedCharMap 应该是DataIndexedCharMapR 应该是r

标签: java inheritance data-structures casting trie


【解决方案1】:

从您的代码看来,dataIndexedCharMap 总是会有TreeNode 类型的项目。在这种情况下,无需创建对象数组并将其转换为 TreeNode。您可以创建 TreeNode[] 数组而不是 Object[] 数组并删除您添加的所有泛型。

public static class dataIndexedCharMap {
    private TreeNode[] items;
    public dataIndexedCharMap(int R) {
        items =  new TreeNode[R];
    }
}

【讨论】:

  • 很好的解决方案,谢谢!但我仍然很好奇为什么我之前的工作失败了。为什么我们不能将 object[ ] 数组转换为每个元素都是 TreeNode 的数组
  • 当你向下转换时,你需要确保被向下转换的对象实际上是你向下转换到的对象的实例。在您的情况下,Object 数组被强制转换为 TreeNode 数组。由于这不满足上述条件,您会得到一个 ClassCastException。为了更好地理解,您可以查看stackoverflow.com/questions/4862960/…
猜你喜欢
  • 1970-01-01
  • 2015-10-18
  • 2014-05-09
  • 2015-02-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-23
  • 2011-06-06
  • 1970-01-01
相关资源
最近更新 更多