• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

runtime exception during accessing elements in hashmap

 
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
MyEclipse IDE Firefox Browser Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 9697
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
siddharth please Use Code Tags when you post a source code...
 
Seriously Rick? Seriously? You might as well just read this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic