tags:

views:

104

answers:

5

How remove the:

Type safety: The expression of type List[] needs unchecked conversion to conform to List<Object>[]

compiler warning in the following expression:

List<Object>[] arrayOfList = new List[10];
+1  A: 
List arrayOfList[] = new List[10];

or

List[] arrayOfList = new List[10];

You can't have generic arrays in Java, so there is no reason to have a reference to one. It would not be type-safe, hence the warning. Of course, you're using <Object>, which means your lists are intended to contain any object. But the inability to have generic arrays still applies.

Also, note that the second version above (with [] attached to the type) is usually considered better style in Java. They are semantically equivalent.

Matthew Flaschen
+1  A: 

There are a number of ways:

  1. You can add `@SuppressWarnings("unchecked") before the assignment to tell the compiler to ignore the warning
  2. Use raw types List[] arrayOfList = new List[10]; notice that in Java you usually put the [] after the type not the variable when declaring it - though using raw types is discouraged by Sun since they might be removed in a future version.
  3. Don't use arrays, it's usually a bad idea to mix collections with arrays: List<List<Object>> listOfList = new ArrayList<List<Object>>;
Andrei Fierbinteanu
+2  A: 

Afaik the only way is to use @SuppressWarnings("unchecked"). At least if you want to avoid the raw type warning that occurs in Matthew's answer.

But you should rethink your design. An Array of Lists? Is that really necessary? Why not a List of Lists? And if it gets too complicated (a List of List of Map of List to...), use custom data types. This really makes the code much more readable.

And as an unrelated side note: You should write List<Object>[] arrayOfList. The brackets are part of the type, not the variable.

musiKk
+1  A: 

You cannot do any variation of this without a compiler warning. Generics and arrays do not play nice. Though you can suppress it with

@SuppressWarnings("unchecked")
final List<Object> arrayOfList[] = new List[10];
jvdneste
A: 

Unfortunately, due to the fact that generics are implemented in Java using type erasure, you cannot create an array of a type with type parameters:

// This will give you a compiler error
List<Object>[] arrayOfList = new ArrayList<Object>[10];

See this in Angelika Langer's Java Generics FAQ for a detailed explanation.

You could remove the generics and use raw types, as Matthew Flaschen shows, or use a collection class instead of an array:

List<List<Object>> data = new ArrayList<List<Object>>();
Jesper
-1. My code compile because I am here instantiating an Array an not a list.
Manuel Selva
Ok, you're right. My mistake. Edited the anwer. But the important thing to understand here is that you can't create an array of a parameterized type.
Jesper