4

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

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。但是,我找不到有关迭代器的更多信息。我想知道处理中是否支持迭代器?或者我应该导入一些库以便我能够使用它们?

4

2 回答 2

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
    }
}
于 2012-12-22T18:04:52.307 回答
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 循环Iterator完全不需要使用 an 并且使代码更加简单。请注意,这也可以用于数组以消除对索引的需求:

String[] strs = {"foo", "bar"};
for (String str : strs)
    System.out.println(str);
于 2012-12-22T17:37:32.400 回答