Re: forEach and Casting
On Apr 22, 2:23 pm, Patricia Shanahan <p...@acm.org> wrote:
Jason Cavett wrote:
I have a question about the use of the foreach statement in Java 1.5.
Currently, the collection I'm using an Iterator over contains objects
of a Generic type (an abstract class). When I get the object from the
collection, I must cast it to the more specific type so I can use the
various methods. There is no way to change this.
Is there any way, using the foreach statement in place of using an
Iterator, to cast to the right type? I'm thinking something like
this...
Collection<Generic> genericCollection = new ArrayList<Generic>();
genericColelction = doSomeStuffToGetGenericCollection();
// this is the part I'm not sure about - can I even do something like
this?
for(Specific o : (Specific) genericCollection) {
// do stuff
}
How about this?
for(Generic oGeneric : genericCollection) {
Specific o = (Specific)oGeneric;
// do stuff using o
}
Patricia- Hide quoted text -
- Show quoted text -
Yeah, I thought about that, but it (somewhat) defeated the purpose for
me to move to the new foreach loops, anyway.
I decided to go with something like this:
ArrayList<Specific> var = (ArrayList<Specific>)
getDirectDescendentsOfType(Class classType)
And my getDirectDescendentsOfType is defined as...
public ArrayList<? extends Generic> getDirectDescendentsOfType(Class
classType) {
// stuff
}
It works well. The only downside is I get a warning every time I
perform the cast above. So, I have to add @SuppressWarnings statement
to methods that have this within them. Not a major thing, just
somewhat of a pain.
(I'm going to stick with this method unless anybody has any other
suggestions.)
Thanks again.