I'm trying to create an array of the nested class Key
which uses type variables/parameters from the main class BTree
, but I can't get rid of the ClassCastException
at runtime. I'm not very good with generics in Java, I'd appreciate if someone let me know what the issue is and how to fix it.
public class BTree<T extends Comparable<T>, V> {
//...
private class Node {
public int n;
public boolean isLeaf = false;
public Key[] keys = (Key[]) new Comparable[2 * MIN_DEGREE - 1]; //ClassCastException
public Node[] children = (Node[]) new Object[2 * MIN_DEGREE];
}
private class Key implements Comparable<Key> {
public T key;
public V val;
public Key(T key, V val) {
this.key = key;
this.val = val;
}
public boolean lessThan(Key that) {
return this.key.compareTo(that.key) < 0;
}
public boolean greaterThan(Key that) {
return this.key.compareTo(that.key) > 0;
}
@Override
public int compareTo(Key that) {
if (this.lessThan(that)) return -1;
if (this.greaterThan(that)) return 1;
return 0;
}
}
//....
}
Edit:
I also tried casting Object
array to Key
array and it throws ClassCastException
as well:
public Key[] keys = (Key[]) new Object[2 * MIN_DEGREE - 1];
And when I create Key
array without casting it gives Generic array creation
error when compiling:
public Key[] keys = new Key[2 * MIN_DEGREE - 1];