1

I have a Box class which holds a value and I want to create an array of this class.

Box Class:

public class Box<T> {
    public T t;
    public Box(T t){ this.t = t; }
}

Test Class:

public class Test {
    public static void main(String[] args) {
        Box<Integer>[] arr = new Box<Integer>[10];
    }
}

Compiler says :

Cannot create a generic array of Box

I wonder that why we cant do that and how can I do that?

4 Answers4

2

Java does not allow generic arrays.

You can find more info here: Java Generics FAQ.

For a quick fix, use List (or ArrayList) instead of Array.

List<Box<Integer>> arr = new ArrayList<Box<Integer>>();

Detailed explanation of the issue: Java theory and practice: Generics gotchas:

flavian
  • 28,161
  • 11
  • 65
  • 105
1

This used to work(generates a warning), should still do what you need:

 Box<Integer> arr = (Box<Integer>[]) new Box[10];
Captain Skyhawk
  • 3,499
  • 2
  • 25
  • 39
0

No, you can't because of type erasure, there are two possible workarounds:

  • use an ArrayList<Box<Integer>>
  • use reflection (but you will have warnings) through java.lang.reflect.Array.newInstance(clazz, length)
Jack
  • 131,802
  • 30
  • 241
  • 343
0
Box<Integer> arr = (Box<Integer>[])new Box<?>[10];
newacct
  • 119,665
  • 29
  • 163
  • 224