【发布时间】: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应该是DataIndexedCharMap而R应该是r。
标签: java inheritance data-structures casting trie