Win a copy of Testing JavaScript Applications this week in the HTML Pages with CSS and JavaScript 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
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

Iterating through a treeMap

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Firstly sorry for posting this under forum as i couldnt find a forum for corejava.

I have a tree. How can i get the values of the TreeMap where the values are objects of a class..

can anyone help me out in this...

thanks in advance

regards
jo
 
Bartender
Posts: 10777
71
Hibernate Eclipse IDE Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Jyothi Thummalapenta wrote:I have a tree. How can i get the values of the TreeMap where the values are objects of a class..


I'm sorry, but that doesn't make much sense. Do you mean how do you get the objects held in a TreeMap (as opposed to the keys)?

If so, there are a few ways, but the simplest is to use the values() method, which will return you all the values in the Map, in key order, as a Collection.

I also strongly suggest that you type your Map as well. The keys are plainly Strings, and the values are Map1s (a very bad name, i might add), so tell Java that, viz:
Map<String, Map1> mp = new TreeMap<String, Map1>();

Winston
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You get a ClassCastException because what the iterator provides you are Map.Entry objects, not Map1 objects.

Change lines 38 and 39 to this:


As Winston already suggested, it would be much better if you would use generics, then you would not need casts at all and you couldn't get a ClassCastException.
 
Jyothi Thummalapenta
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanq Jasper...now i got it:)
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
    Bookmark Topic Watch Topic
  • New Topic