319

What's the reason why Java doesn't allow us to do

private T[] elements = new T[initialCapacity];

I could understand .NET didn't allow us to do that, as in .NET you have value types that at run-time can have different sizes, but in Java all kinds of T will be object references, thus having the same size (correct me if I'm wrong).

What is the reason?

5
  • 39
    What are you talking about? You can absolutely do this in .NET. -- I'm here trying to figure out why I can't do it in Java. Oct 5, 2014 at 7:22
  • @BrainSlugs83 - please add a link to some code example or tutorial which shows that.
    – MasterJoe
    Apr 3, 2020 at 22:57
  • Also see - stackoverflow.com/questions/21577493/…
    – MasterJoe
    Apr 6, 2020 at 0:15
  • 1
    @MasterJoe2 the above code in the OP's question is what I'm referring to. It works fine in C#, but not in Java. -- The question states it works in neither, which is incorrect. -- Not sure there's value in discussing it further. Apr 6, 2020 at 2:24
  • [Because it's a bug that hasn't been fixed yet. ](i.stack.imgur.com/hlOJI.jpg)
    – Meech
    Dec 11, 2020 at 2:54

16 Answers 16

252

It's because Java's arrays (unlike generics) contain, at runtime, information about its component type. So you must know the component type when you create the array. Since you don't know what T is at runtime, you can't create the array.

22
  • 34
    But what about erasure? Why doesn't that apply? Mar 5, 2013 at 8:22
  • 17
    How does ArrayList <SomeType> do it then?
    – Thumbz
    Mar 25, 2014 at 23:55
  • 13
    @Thumbz: You mean new ArrayList<SomeType>()? Generic types do not contain the type parameter at runtime. The type parameter is not used in creation. There is no difference in the code generated by new ArrayList<SomeType>() or new ArrayList<String>() or new ArrayList() at all.
    – newacct
    Mar 26, 2014 at 0:05
  • 11
    I was asking more about how ArrayList<T> works with its' private T[] myArray. Somewhere in the code, it must have an array of generic type T, so how?
    – Thumbz
    Mar 26, 2014 at 1:02
  • 23
    @Thumbz: It doesn't have an array of runtime type T[]. It has an array of runtime type Object[], and either 1) the source code contains a variable of Object[] (this is how it is in the latest Oracle Java source); or 2) the source code contains a variable of type T[], which is a lie, but doesn't cause problems due to T being erased inside the scope of the class.
    – newacct
    Mar 26, 2014 at 2:44
152

Quote:

Arrays of generic types are not allowed because they're not sound. The problem is due to the interaction of Java arrays, which are not statically sound but are dynamically checked, with generics, which are statically sound and not dynamically checked. Here is how you could exploit the loophole:

class Box<T> {
    final T x;
    Box(T x) {
        this.x = x;
    }
}

class Loophole {
    public static void main(String[] args) {
        Box<String>[] bsa = new Box<String>[3];
        Object[] oa = bsa;
        oa[0] = new Box<Integer>(3); // error not caught by array store check
        String s = bsa[0].x; // BOOM!
    }
}

We had proposed to resolve this problem using statically safe arrays (aka Variance) bute that was rejected for Tiger.

-- gafter

(I believe it is Neal Gafter, but am not sure)

See it in context here: http://forums.sun.com/thread.jspa?threadID=457033&forumID=316

6
  • 3
    Note that I made it a CW since the answer is not mine.
    – Bart Kiers
    May 28, 2010 at 7:55
  • 12
    This explains why it might not be typesafe. But type safety issues could be warned by the compiler. The fact is that it is not even possible to do it, for almost the same reason why you cannot do new T(). Each array in Java, by design, stores the component type (i.e. T.class) inside it; therefore you need the class of T at runtime to create such an array.
    – newacct
    May 29, 2010 at 23:56
  • 2
    You still can use new Box<?>[n], which might be sometimes sufficient, although it wouldn't help in your example. Jul 2, 2012 at 7:58
  • 1
    @BartKiers I don't get it... this still does not compile (java-8) : Box<String>[] bsa = new Box<String>[3]; did anything change in java-8 and up I assume?
    – Eugene
    Mar 12, 2018 at 12:32
  • 1
    @Eugene, Arrays of specific generic types simply aren't allowed becuase they can lead to a loss of type safety as demonstrated in the sample. It is not allowed in any version of Java. The answer starts as "Arrays of generic types are not allowed because they're not sound. "
    – garnet
    Jan 1, 2019 at 13:56
67

By failing to provide a decent solution, you just end up with something worse IMHO.

The common work around is as follows.

T[] ts = new T[n];

is replaced with (assuming T extends Object and not another class)

T[] ts = (T[]) new Object[n];

I prefer the first example, however more academic types seem to prefer the second, or just prefer not to think about it.

Most of the examples of why you can't just use an Object[] equally apply to List or Collection (which are supported), so I see them as very poor arguments.

Note: this is one of the reasons the Collections library itself doesn't compile without warnings. If this use-case cannot be supported without warnings, something is fundamentally broken with the generics model IMHO.

7
  • 6
    You have to be careful with the second one. If you return the array created in such a way to someone who expects, say, a String[] (or if you store it in a field that is publicly accessible of type T[], and someone retrieves it), then they will get a ClassCastException.
    – newacct
    May 30, 2010 at 0:01
  • 7
    I voted this answer down because your preferred example is not permitted in Java and your second example may throw a ClassCastException Jan 31, 2014 at 2:27
  • 5
    @JoséRobertoAraújoJúnior It is quite clear the first example needs to be replaced with the second example. It would be more helpful for you to explain why the second example can throw a ClassCastException as it wouldn't be obvious to everyone. Feb 1, 2014 at 8:48
  • 4
    @PeterLawrey I created a self-answered question showing why T[] ts = (T[]) new Object[n]; is a bad idea: stackoverflow.com/questions/21577493/… Feb 5, 2014 at 12:40
  • 1
    @MarkoTopolnik I should be given a medal for answering all your comments to explain the same thing I've already said, the only thing that changed from my original reason is that I though that he said T[] ts = new T[n]; was a valid example. I'll keep the vote because he's answer can cause issues and confusions to other devs and is also off-topic. Also, I'll stop comment about this. Feb 5, 2014 at 13:32
37

The reason this is impossible is that Java implements its Generics purely on the compiler level, and there is only one class file generated for each class. This is called Type Erasure.

At runtime, the compiled class needs to handle all of its uses with the same bytecode. So, new T[capacity] would have absolutely no idea what type needs to be instantiated.

0
22

The answer was already given but if you already have an Instance of T then you can do this:

T t; //Assuming you already have this object instantiated or given by parameter.
int length;
T[] ts = (T[]) Array.newInstance(t.getClass(), length);

Hope, I could Help, Ferdi265

3
  • 1
    This is a nice solution. But this will get unchecked warnings (cast from Object to T[]). Another "slower" but "warning-free" solution would be: T[] ts = t.clone(); for (int i=0; i<ts.length; i++) ts[i] = null;.
    – midnite
    Jul 20, 2013 at 17:46
  • 1
    In addition, if what we kept is T[] t, then it would be (T[]) Array.newInstance(t.getClass().getComponentType(), length);. i did spend some times to figure out getComponentType(). Hope this helps others.
    – midnite
    Jul 26, 2013 at 16:42
  • 1
    @midnite t.clone() will not return T[]. Because t is not Array in this answer.
    – xmen
    Sep 25, 2014 at 2:02
6

The main reason is due to the fact that arrays in Java are covariant.

There's a good overview here.

4
  • I don't see how you could support "new T[5]" even with invariant arrays. May 29, 2010 at 8:19
  • 3
    @DimitrisAndreou Well, the whole thing is rather a comedy of errors in the Java design. It all started with array covariance. Then, once you have array covariance, you can cast String[] to Object and store an Integer in it. So then they had to add a runtime type check for array stores (ArrayStoreException) because the issue could not be caught at compile-time. (Otherwise, an Integer actually could be stuck in a String[], and you would get an error when you tried to retrieve it, which would be horrible.) ... Dec 24, 2014 at 15:46
  • 3
    @DimitrisAndreou … Then, once you have put a runtime check in place of a far sounder compile-time check, you run into type erasure (also an unfortunate design flaw -- included only for backward compatibility). Type erasure means that you can't do runtime type checks for generic types. So therefore, to avoid the array storage type problem, you simply can't have generic arrays. If they had simply made arrays invariant in the first place, we could just do compile-time type checks without running afoul of erasure. Dec 24, 2014 at 15:49
  • … I have just discovered the five-minute editing period for comments. Object should have been Object[] in my first comment. Dec 24, 2014 at 15:59
3

I like the answer indirectly given by Gafter. However, I propose it is wrong. I changed Gafter's code a little. It compiles and it runs for a while then it bombs where Gafter predicted it would

class Box<T> {

    final T x;

    Box(T x) {
        this.x = x;
    }
}

class Loophole {

    public static <T> T[] array(final T... values) {
        return (values);
    }

    public static void main(String[] args) {

        Box<String> a = new Box("Hello");
        Box<String> b = new Box("World");
        Box<String> c = new Box("!!!!!!!!!!!");
        Box<String>[] bsa = array(a, b, c);
        System.out.println("I created an array of generics.");

        Object[] oa = bsa;
        oa[0] = new Box<Integer>(3);
        System.out.println("error not caught by array store check");

        try {
            String s = bsa[0].x;
        } catch (ClassCastException cause) {
            System.out.println("BOOM!");
            cause.printStackTrace();
        }
    }
}

The output is

I created an array of generics.
error not caught by array store check
BOOM!
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
    at Loophole.main(Box.java:26)

So it appears to me you can create generic array types in java. Did I misunderstand the question?

29
  • Your example is different from what I've asked. What you described are the dangers of array covariance. Check it out (for .NET : blogs.msdn.com/b/ericlippert/archive/2007/10/17/… ) May 28, 2010 at 11:28
  • Hopefully you get a type-safety warning from the compiler, yes? May 28, 2010 at 11:34
  • 1
    Yes, I get a type-safety warning. Yes, I see that my example is not responsive to the question.
    – emory
    May 28, 2010 at 11:51
  • Actually you get multiple warnings due to sloppy initialization of a,b,c. Also, this is well known and affects the core library, e.g. <T>java.util.Arrays.asList(T...). If you pass any non-reifiable type for T, you get a warning (because the created array has a less precise type than the code pretends), and it's super ugly. It would be better if the author of this method got the warning, instead of emitting it at usage site, given that the method itself is safe, it doesn't expose the array to the user. May 29, 2010 at 8:34
  • 1
    You did not create a generic array here. The compiler created a (non-generic) array for you.
    – newacct
    May 29, 2010 at 23:57
3

In my case, I simply wanted an array of stacks, something like this:

Stack<SomeType>[] stacks = new Stack<SomeType>[2];

Since this was not possible, I used the following as a workaround:

  1. Created a non-generic wrapper class around Stack (say MyStack)
  2. MyStack[] stacks = new MyStack[2] worked perfectly well

Ugly, but Java is happy.

Note: as mentioned by BrainSlugs83 in the comment to the question, it is totally possible to have arrays of generics in .NET

3

From Oracle tutorial:

You cannot create arrays of parameterized types. For example, the following code does not compile:

List<Integer>[] arrayOfLists = new List<Integer>[2];  // compile-time error

The following code illustrates what happens when different types are inserted into an array:

Object[] strings = new String[2];
strings[0] = "hi";   // OK
strings[1] = 100;    // An ArrayStoreException is thrown.

If you try the same thing with a generic list, there would be a problem:

Object[] stringLists = new List<String>[];  // compiler error, but pretend it's allowed
stringLists[0] = new ArrayList<String>();   // OK
stringLists[1] = new ArrayList<Integer>();  // An ArrayStoreException should be thrown,
                                            // but the runtime can't detect it.

If arrays of parameterized lists were allowed, the previous code would fail to throw the desired ArrayStoreException.

To me, it sounds very weak. I think that anybody with a sufficient understanding of generics, would be perfectly fine, and even expect, that the ArrayStoredException is not thrown in such case.

2
  • This is true that genericized arrays cannot be created not due to the fact that type erasure is in place...since the types are erased at compile time, new instantiation of List class is possible only without its generic type...hence
    – mahee96
    Jun 16, 2021 at 22:34
  • how can one allow such usage...one way would be to stop doing type erasure + retain different versions of the class byte code for different generic types as in C++ templates....then the above syntax of genericized array instantiation is completely valid............List<Integer>[] arrayOfLists = new List[2]; // is completely valid since the List interface itself is the only things that remains after generic paramter type info is erased by the compiler.
    – mahee96
    Jun 16, 2021 at 22:40
2

class can declare an array of type T[], but it cannot directly instantiate such an array. Instead, a common approach is to instantiate an array of type Object[], and then make a narrowing cast to type T[], as shown in the following:

  public class Portfolio<T> {
  T[] data;
 public Portfolio(int capacity) {
   data = new T[capacity];                 // illegal; compiler error
   data = (T[]) new Object[capacity];      // legal, but compiler warning
 }
 public T get(int index) { return data[index]; }
 public void set(int index, T element) { data[index] = element; }
}
1

It is because generics were added on to java after they made it, so its kinda clunky because the original makers of java thought that when making an array the type would be specified in the making of it. So that does not work with generics so you have to do E[] array=(E[]) new Object[15]; This compiles but it gives a warning.

0

There surely must be a good way around it (maybe using reflection), because it seems to me that that's exactly what ArrayList.toArray(T[] a) does. I quote:

public <T> T[] toArray(T[] a)

Returns an array containing all of the elements in this list in the correct order; the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list.

So one way around it would be to use this function i.e. create an ArrayList of the objects you want in the array, then use toArray(T[] a) to create the actual array. It wouldn't be speedy, but you didn't mention your requirements.

So does anyone know how toArray(T[] a) is implemented?

1
  • 3
    List.toArray(T[]) works because you are essentially giving it the component type T at runtime (you are giving it an instance of the desired array type, from which it can get the array class, and then, the component class T). With the actual component type at runtime, you can always create an array of that runtime type using Array.newInstance(). You'll find that mentioned in many question that ask how to create an array with a type unknown at compile time. But the OP was specifically asking why you can't use the new T[] syntax, which is a different question
    – newacct
    Nov 23, 2011 at 22:22
0

If we cannot instantiate generic arrays, why does the language have generic array types? What's the point of having a type without objects?

The only reason I can think of, is varargs - foo(T...). Otherwise they could have completely scrubbed generic array types. (Well, they didn't really have to use array for varargs, since varargs didn't exist before 1.5. That's probably another mistake.)

So it is a lie, you can instantiate generic arrays, through varargs!

Of course, the problems with generic arrays are still real, e.g.

static <T> T[] foo(T... args){
    return args;
}
static <T> T[] foo2(T a1, T a2){
    return foo(a1, a2);
}

public static void main(String[] args){
    String[] x2 = foo2("a", "b"); // heap pollution!
}

We can use this example to actually demonstrate the danger of generic array.

On the other hand, we've been using generic varargs for a decade, and the sky is not falling yet. So we can argue that the problems are being exaggerated; it is not a big deal. If explicit generic array creation is allowed, we'll have bugs here and there; but we've been used to the problems of erasure, and we can live with it.

And we can point to foo2 to refute the claim that the spec keeps us from the problems that they claim to keep us from. If Sun had more time and resources for 1.5, I believe they could have reached a more satisfying resolution.

0

As others already mentioned, you can of course create via some tricks.

But it's not recommended.

Because the type erasure and more importantly the covariance in array which just allows a subtype array can be assigned to a supertype array, which forces you to use explicit type cast when trying to get the value back causing run-time ClassCastException which is one of the main objectives that generics try to eliminate: Stronger type checks at compile time.

Object[] stringArray = { "hi", "me" };
stringArray[1] = 1;
String aString = (String) stringArray[1]; // boom! the TypeCastException

A more direct example can found in Effective Java: Item 25.


covariance: an array of type S[] is a subtype of T[] if S is a subtype of T

0

T vals[]; // OK

But, you cannot instantiate an array of T // vals = new T[10]; // can't create an array of T

The reason you can’t create an array of T is that there is no way for the compiler to know what type of array to actually create.

-2

Try this:

List<?>[] arrayOfLists = new List<?>[4];
2
  • This actually works and does not throw any compile time errors. Can anyone please explain this? Jul 16 at 14:58
  • 1
    @AdityaMayukhSom Also List[] array = new List[4] would work, because "List" is reifiable. That is, it's a "real" type at runtime even after erasure. Per JLS 15.10 the type in an array creation expression must be "reifiable." Per JLS 4.7 a type may be reifiable if type parameters are wildcards. The wildcards mean you don't know what it's a List of, limiting what you can do to safe operations the same way raw types do.
    – Ben
    Aug 4 at 23:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.