Re: Generics in Arrays
"Wojtek Bok" <wb@nospam.com> wrote in message
news:1WXLg.11099$Hr1.688@clgrps12...
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.
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