Re: Help with an arraylist of subclass using generics
Alessandro wrote:
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
As you've noticed, each next() call advances the Iterator
to the next element of the list, leaving behind the one you
care about. The solution is to call next() just once per
element, stash the reference in a local variable, and then
make your subsequent tests on that variable:
Iterator ... iter1 = ...;
while (iter1.hasNext()) {
RicDataElement obj = iter1.next(); // or even "Object obj"
if (obj instanceof RicDataCrossElement) {
RicDataCrossElement rdce = (RicDataCrossElement)obj;
...
}
...
}
You can simplify this a little bit by using the "for each"
syntax and letting Java take care of the Iterator for you:
for (RicDataElement obj : buffer) {
if (obj instanceof ...
}
As an aside, it is usually -- not always, but usually --
not a good idea to use this kind of "instanceof" logic to
make decisions in the program. I don't know enough about the
purposes of your RicXXX classes to suggest exactly what to do
instead, but instead of having your code say "This one's a
monkey so I'll feed it a banana, that one's a bird so I'll
feed it a worm," it is usually better to say to each of them
"You know what your favorite food is: go get some and eat it."
--
Eric.Sosman@sun.com