If I have a ArrayList which will hold items of type MyItem, then I declare it as:
-----------------------------------------------------------
ArrayList<MyItem> items = new ArrayList<MyItem>();
-----------------------------------------------------------
I then have a ArrayList which holds these items:
-----------------------------------------------------------
ArrayList<ArrayList<MyItem>> allItems = new ArrayList<ArrayList<MyItem>>();
-----------------------------------------------------------
I can then get an array of the items as:
-----------------------------------------------------------
ArrayList[] itemList = allItems.toArray(new ArrayList[0]);
-----------------------------------------------------------
Ok, now to get at each ArrayList<MyItem> I should be able to:
-----------------------------------------------------------
ArrayList<MyItem> itemArray;
for ( int c = 0; c < itemList.length; c++ )
itemArray = itemList[c];
-----------------------------------------------------------
Except that the compiler complains about type safety in the last line. Fair enough, I have an generic ArrayList I am trying to put into an
ArrayList<MyItem>.
So how do I keep the compiler happy (other than add suppress warnings "unchecked" for the entire method)?
I tried:
-----------------------------------------------------------
ArrayList<MyItem>[] itemList = allItems.toArray(new ArrayList<MyItem>[0]);
-----------------------------------------------------------
but that causes other errors.
Oliver Wong - 07 Sep 2006 18:46 GMT
> If I have a ArrayList which will hold items of type MyItem, then I declare
> it as:
[quoted text clipped - 32 lines]
> -----------------------------------------------------------
> but that causes other errors.
Why are you bringing arrays into the situation?
ArrayList<ArrayList<MyItem>> allItems = new ArrayList<ArrayList<MyItem>>();
for (ArrayList<MyItem> itemList : allItems) {
/*do something with each item list*/
}
- Oliver
Wojtek Bok - 07 Sep 2006 19:00 GMT
> Why are you bringing arrays into the situation?
>
> ArrayList<ArrayList<MyItem>> allItems = new ArrayList<ArrayList<MyItem>>();
> for (ArrayList<MyItem> itemList : allItems) {
> /*do something with each item list*/
> }
Sigh.
I need to get away for a few days to learn more about 1.5
But there still seems to be a gap in the spec. I SHOULD be able to set up an array with a generic.
Thanks!
Oliver Wong - 07 Sep 2006 20:23 GMT
> But there still seems to be a gap in the spec. I SHOULD be able to set up
> an array with a generic.
There's a lot of problems with generics and arrays, actually. Due to the
fact that one of them is covariant and the other isn't, or something like
that.
- Oliver