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
  • 26,242
  • 10
  • 57
  • 95
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,415
  • 1
  • 21
  • 37
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
  • 125,196
  • 27
  • 216
  • 324
0
Box<Integer> arr = (Box<Integer>[])new Box<?>[10];
newacct
  • 110,405
  • 27
  • 152
  • 217