• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

runtime exception during accessing elements in hashmap

 
siddharth das
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Anastasia Sirotenko
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Ankit Garg
Sheriff
Posts: 9521
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
siddharth please Use Code Tags when you post a source code...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic