How to iterate over a collection of a Map
How to iterate over a collection of a Map
I get a ClassCastException when doing the following pls help:
ollection all=CDA.getC(VO);//some method returnign a collection
for (Iterator it=all.iterator(); it.hasNext(); ) {
HashMap element =(HashMap) it.next();
for(Iterator j=element.entrySet().iterator(); j.hasNext(); ) {
Map.Entry e = (Map.Entry) j.next();
String key=(String)e.getKey();
String value=(String)e.getValue();
[478 byte] By [
Rhea1978a] at [2007-11-27 11:26:17]

# 3
> Basically this collection is returned by a query to
> the database and it is in the form of collection of
> maps.
> and yes both the keys and values are of string
On what line is the ClassCastException happening?
> i am using jdk 1.4
Ok. If you were on a later version, you would have other, more typesafe options here, but no matter
# 5
> HashMap element =(HashMap) it.next();
Then the collection doesn't contain HashMaps. Where is this collection coming from? Try casting it to java.util.Map, if some ORM layer is returning this collection it may be some proprietary implementation
# 9
> but again a problem how about if some of the values
> in the returned map is null and i need to access
> those values I will get a nullpointerexception when I
> try to do
> e.getValue().toString()
Don't do toString on the values! Cast them to string as you were, the CCE will be a lot clearer to fix than a rogue NPE
# 10
e.getValue() may contain NULL. Thats why you should not do a toString(). Just cast it to String (String).
If you are sure of calling toString(), check for NULL before doing so, to avoid NullPointerException
if (e.getValue() != null) {
e.getValue().toString();
}
http://eathumblepie.blogspot.com
Message was edited by:
saracgi