I have written my own 2-3-4 tree in java. Currently, my code looks like this:
public class tree234{
private class node{
Comparable data[]=new Comparable[3];
node next[]=new node[4];
}
}
Instead, I'd like to have something like this:
public class tree234<T extends Comparable<? super T>>{
private class node{
T[] data=new T[3];//error here!
node[] next=new node[4];
}
}
While I understand that I cannot create the array (and sort of understand why), I can't think of a reasonably simple way to implement the node class with generics. Any suggestions?
You can always do an explicit cast...
The variable T[] will end up as a Comparable[] in the compiled class since T extends Comparable. So the array type must be Comparable[]
- you can't assign an Object
object to a Comparable
variable, .
The other array type is Tree234.Node[]
.
public class Tree234<T extends Comparable<? super T>>{
private class Node{
T[] data=(T[]) new Comparable[3]; // need to be a comparable, as the superclass is known.
Node[] next = (Node[]) new Tree234.Node[4];
}
}