I'm trying to implement a trie in Java. When I test if my method "insert" works, I got the error below.
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)
I also went through some similar questions but still can't figure it out. I'm wondering why we can't cast the type from Object to TreeNode[] array.
My code is as follows. I know using dataIndexedCharMap by array wasted a lot of memory (HashTable or BST would be a better way), but I'm just trying to compare the memory and efficiency of these three methods but got some trouble.
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");
}
}
From your code it looks like dataIndexedCharMap
is always going to have items of type TreeNode
. In that case, there is no need to create an object array and cast it to TreeNode. You can create TreeNode[]
array instead of Object[]
array and remove all the generics that you have added.
public static class dataIndexedCharMap {
private TreeNode[] items;
public dataIndexedCharMap(int R) {
items = new TreeNode[R];
}
}