• Post Reply Bookmark Topic Watch Topic
  • New Topic

Iterating through a treeMap  RSS feed

 
Jyothi Thummalapenta
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
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate 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
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • 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
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!