2012-12-22 151 views
4

我希望在Processing中使用HashMap,我希望使用迭代器来遍历HashMap中的所有条目。但是,当我希望使用迭代器时,我被告知“无法找到名为Iterator的类或类型”。部分代码如下所示。Processing是否支持迭代器?

Iterator i = nodeTable.entrySet().iterator(); // Get an iterator 
while (i.hasNext()) 
{ 
    Node nodeDisplay = (Node)i.next(); 
    nodeDisplay.drawSelf(); 
} 

从处理网站http://processing.org/reference/HashMap.html我知道迭代器可以用于遍历HashMap中。不过,我找不到更多关于迭代器的信息。我想知道是否在处理中支持迭代器?或者我应该导入一些库,以便能够使用它们?

+2

你是否'import java.util.Iterator;'? –

+1

此外,使用泛型使您的代码类型安全。 –

+0

谢谢!我没有导入它。我只是试图导入java.util.Iterator,但我被告知i.next()不能转换为类节点,它是一个自定义的类。 @ A - C – Timothy

回答

1

很高兴你解决了你的问题,但对于其他人来说,如果你想迭代entrySet(),有两种方法。这样做的第一种方式:

import java.util.HashMap; 
import java.util.Iterator; 
import java.util.Map; 
import java.util.Map.Entry; 

public class Testing { 

    public static void main(String[] args) { 
     Map<String, String> strMap = new HashMap<String, String>(); 
     strMap.put("foo", "bar"); 
     strMap.put("alpha", "beta"); 
     for (Iterator<Entry<String, String>> iter = strMap.entrySet().iterator(); iter.hasNext();) 
     { 
      Entry<String, String> entry = iter.next(); 
      System.out.println(entry.getKey() + "=" + entry.getValue()); 
     } 
    } 
} 

注意的进口在代码的顶部,你可能错过了一个为Iterator

而第二个:

import java.util.HashMap; 
import java.util.Map; 
import java.util.Map.Entry; 

public class Testing { 

    public static void main(String[] args) { 
     Map<String, String> strMap = new HashMap<String, String>(); 
     strMap.put("foo", "bar"); 
     strMap.put("alpha", "beta"); 
     for (Entry<String, String> entry : strMap.entrySet()) 
      System.out.println(entry.getKey() + "=" + entry.getValue()); 
    } 
} 

这就是所谓的for-each loop,并且消除了需要使用Iterator所有和使代码更简单。请注意,这也可以在阵列中使用,以消除对索引的需要:只要我有问题解决了

String[] strs = {"foo", "bar"}; 
for (String str : strs) 
    System.out.println(str); 
+0

非常感谢您的热心帮助。 – Timothy

2

,我会把我的部分代码在这里情况下,其他人可能遇到此。再次感谢您的亲切帮助。

import java.util.Iterator; // Import the class of Iterator 
// Class definition and the setup() function are omitted for simplicity 

// The iterator is used here 
HashMap<String, Node> nodeTable = new HashMap<String, Node>(); 
void draw(){ 
    // Part of this function is omitted 
    Iterator<Node> i = nodeTable.values().iterator(); 
    // Here I use the iterator to get the nodes stored the hashtable and I use the function values() here. entrySet() or keySet() can also be used when necessary 
    while (i.hasNext()) { 
     Node nodeDisplay = (Node)i.next(); 
     // Now you can use the node from the hashmap 
    } 
}