wood burning stoves*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes runtime exception  during accessing elements in hashmap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "runtime exception  during accessing elements in hashmap" Watch "runtime exception  during accessing elements in hashmap" New topic
Author

runtime exception during accessing elements in hashmap

siddharth das
Ranch Hand

Joined: Aug 17, 2007
Posts: 124
Hi,

I made a HashMap<String, Integer>. I want to iterator over all elements.

for (Iterator it = m_Table.values().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry)it.next();
String strKey = (String)entry.getKey()
Integer nData = (Integer)entry.getValue() ;
}

This causes a runtime exception though... what's the right way to do it?

Thanks
Deepak Bala
Bartender

Joined: Feb 24, 2006
Posts: 6661
    
    5

What is the runtime exception ?

Have a look at this -> http://java.sun.com/j2se/1.4.2/docs/api/java/util/HashMap.html#values()

It will help you understand the problem


SCJP 6 articles - SCJP 5/6 mock exams - More SCJP Mocks
Anastasia Sirotenko
Ranch Hand

Joined: Jul 20, 2009
Posts: 64
siddharth das wrote:Hi,

I made a HashMap<String, Integer>. I want to iterator over all elements.



This causes a runtime exception though... what's the right way to do it?

Thanks

You made iterator on values Iterator it = m_Table.values().iterator(); so the objects you get from this iterator you can cast to the value type Integer.
But then you try to cast the object returned by iterator to Map.Entry class, getting ClassCastException


try this code:


[SCJP 6.0]
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9304
    
  17

siddharth please Use Code Tags when you post a source code...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: runtime exception during accessing elements in hashmap