hyyou2010
hyyou2010

Reputation: 877

How to cast list in array? in Java

I'm really confused. My code:

public void testList(){
    int cnt = 3;
    LinkedList<LvRow>[] vListItems = new LinkedList[cnt]; //eclipse suggest warnning
    for (int i = 0; i < cnt; i++) {
        vListItems[i] = new LinkedList<LvRow>();
    }
}

eclipse suggest a warning:

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

It seems a cast problem. I have tried many times, but I don't know how to cast. Anyone can help me?

By the way, if following codes is same, or have any diffence?

 LinkedList<LvRow>[] vListItems = new LinkedList[cnt];
 LinkedList<LvRow> vListItems[] = new LinkedList[cnt];

Upvotes: 1

Views: 337

Answers (3)

Kevin Bowersox
Kevin Bowersox

Reputation: 94469

When using generics you cannot create an array of objects with a generic types. This is because arrays perform an array store check which guarantees an object in the array is of the component type. Since type erasure removes type arguments the exact type of the array cannot be known at runtime. Read More

You can work around this limitation by creating a List<List<LvRow>>.

List<List<LvRow>>[] vListItems = new LinkedList<List<LvRow>>(); 

Upvotes: 1

Narendra Pathai
Narendra Pathai

Reputation: 41945

Cannot Create Arrays of Parameterized Types

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.

This all happens because of type erasure.

Solution

you should use List collection for this so that the compiler can do static type checking and provide you type safety.

List<LinkedList<LvRow>> list = new ArrayList<LinkedList<LvRow>>();

Upvotes: 7

Manish Doshi
Manish Doshi

Reputation: 1193

You can use like this:

LinkedList<LvRow>[] vListItems = new LinkedList<LvRow>[cnt];

Upvotes: -1

Related Questions