Win a copy of Java Database Connections & Transactions (e-book only) this week in the JDBC forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Knute Snortum
  • Paul Clapham
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Frits Walraven
Bartenders:
  • Ganesh Patekar
  • Tim Holloway
  • salvin francis

runtime exception during accessing elements in hashmap  RSS feed

 
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
 
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
 
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:
 
Sheriff
Posts: 9643
42
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...
 
Tick check! Okay, I guess that was just an itch. Oh wait! Just a tiny ad:
how do I do my own kindle-like thing - without amazon
https://coderanch.com/t/711421/engineering/kindle-amazon
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!