1

I have this code which gives me the error that "Cannot create a generic array of BST_Node"

    BST_Node<Integer>[] arrayTree = new BST_Node<Integer>[treeSize];

I don't know why because I have

    Integer[] arrayTree = new Integer[treeSize];

and it works perfectly. Why It is that it can't create a fixed size array with a generic type and what's the correct way to do this?

Ali_IT
  • 6,681
  • 7
  • 26
  • 42
  • 2
    http://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#createArrays ; While you can cast to get around this, use an `ArrayList>` and be done with it. – Brian Roach Jan 17 '14 at 04:11

2 Answers2

7
BST_Node<Integer>[] arrayTree = (BST_Node<Integer>[]) new BST_Node[treeSize];

You don't know a type argument at runtime, so you can't create a generic array, but only a rawtype-array.

See a comprehensive explanation here or here

Community
  • 1
  • 1
Philip Voronov
  • 3,789
  • 4
  • 20
  • 32
2

Arrays are Not Generic. Thats why Arrays are checked during compile as well as runtime, where as Collections can be Generic and its checked only during the compile time. So when you declare generic array, you have to do like this:

BST_Node<Integer>[] arrayTree = (BST_Node<Integer>[]) new BST_Node[treeSize]; 
UVM
  • 9,526
  • 5
  • 39
  • 63