This question already has an answer here:
- How to create a generic array in Java? 29 answers
I am trying do something like this:-
public static ArrayList<myObject>[] a = new ArrayList<myObject>[2];
myObject is a class. I am getting this error:- Generic array creation (arrow is pointing to new.)
There is a easier way to create generic arrays than using List.
First, let
Then initialize
It seems to me that you use the wrong type of parenthesis. The reason why you can't define an array of generic is type erasure.
Plus, declaration of you variable "a" is fragile, it should look this way:
Do not use a concrete class when you can use an interface.
You can't have arrays of generic classes. Java simply doesn't support it.
You should consider using a collection instead of an array. For instance,
Another "workaround" is to create an auxilliary class like this
and then create an array of
MyObjectArrayList
.Here is a good article on why this is not allowed in the language. The article gives the following example of what could happen if it was allowed:
if you are trying to declare an arraylist of your generic class you can try:
this will give you an arraylist of myobject (size 10), or if u only need an arraylist of size 2 you can do:
or you may be trying to make an arraylist of arraylists:
although im not sure if the last this i said is correct...
You can do
or
(The former is probably better.) Both will cause unchecked warnings, which you can pretty much ignore or suppress by using: @SuppressWarnings("unchecked")