• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Iterator

 
Maureen Charlton
Ranch Hand
Posts: 218
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My understanding is that the Iterator is a class and the iterator method is of the TreeSet collection which returns an iterator object that is referenced by the a variable say recSet

i.e. to be using TreeSet:

Set tset = new TreeSet( )
I would have the following line of code to display a list using iterator:

Iterator recSet = tset.iterator( );

while (recSet.hasNext( ) )
System.out.println( (String)recSet.next( ) );

However, I am using TreeMap as I needed to store key and value pairs where the key needs to be sorted.

This is where I am getting confused. One of the constrains is we have to declare an Iterator method i.e.

public Iterator getIterator( )

This is where I'm getting confused a little And struggling to find somewhere as an example, where it has been used in a TreeMap. I couldn't find anything in the API when looking under TreeMap.

Is someone able to assist me with explaining how I would implement this in a TreeMap or alternatively point me in the right direction?
 
Warren Dew
blacksmith
Ranch Hand
Posts: 1332
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you want to iterate over the keys in the map? If that's what you want, you may want to check if there are any methods in the TreeMap interface that allow you to get the set of keys.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think Warren is suggesting that you use TreeMap methods to obtain a Set of your TreeMap keys (or perhaps a Collection of its values), then get an iterator for that Collection.
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think it's far more likely that she wants to iterate the key/value pairs. Maybe there's a method in Map that returns a Set of the pair entries...
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by David Harkness:
...Maybe there's a method in Map that returns a Set of the pair entries...

Hmmm, I missed that one. Very interesting...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic