-
Iterator class
Does anyone know the proper way to loop through a collection?
This is a code snippet from a program i am working on and im not sure why i cant use an Iterator on a TreeMap.
Code:
Map stringMap = new TreeMap();
for(Iterator i = stringMap.iterator(); i.hasNext();){
if(stringMap.containsKey(key)){
return stringMap.get(i.next());
}
i.next();
}
I can use it on a LinkedList with no problem.
Code:
import java.util.*;
public class Test{
public static void main(String[] args){
String greeting = "Hello";
String departing = "GoodBye";
List l = new LinkedList();
l.add(greeting);
l.add(departing);
for(Iterator i = l.iterator(); i.hasNext();){
System.out.println(i.next());
}
-
Code:
Map stringMap = new TreeMap();
for(Iterator i = (stringMap.values()).iterator(); i.hasNext(){
if(stringMap.containsKey(key)){
return stringMap.get(i.next());
}
i.next();
}
try that. Map/TreeMap does not have an iterator method, but values() returns a Collection, which does have an iterator.
:)
-
Thanks Bro. Works like butta. You da man..... :p