Manuel Selva
Manuel Selva

Reputation: 19050

Generic List of Array

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];

Upvotes: 2

Views: 464

Answers (5)

Jesper
Jesper

Reputation: 206796

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>>();

Upvotes: 0

Andrei Fierbinteanu
Andrei Fierbinteanu

Reputation: 7826

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>>;

Upvotes: 1

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

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.

Upvotes: 1

jvdneste
jvdneste

Reputation: 1677

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];

Upvotes: 1

musiKk
musiKk

Reputation: 15189

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.

Upvotes: 2

Related Questions