通过HashMap迭代

时间:2011-08-10 07:53:25

标签: search iterator hashmap loops

好的,所以我正在研究搜索方法,搜索的术语在数据库中运行,匹配的产品被添加到带有2个整数字段的hashMap中。

然后在制作hashmap之后,将显示这些项目,但是我无法使用hashmap打印出详细信息

这是我的代码

public HashMap<Integer, Integer> bankSearch = new HashMap<Integer, Integer>();

和使用

    Iterator it = bankSearch.entrySet().iterator();
    while (it.hasNext()) {
        HashMap.Entry pairs = (HashMap.Entry)it.next();
        System.out.println(pairs.getKey() + " = " + pairs.getValue());
        if (bankItemsN[i] > 254) {
            outStream.writeByte(255);
            outStream.writeDWord_v2(pairs.getValue());
        } else {
            outStream.writeByte(pairs.getValue()); // amount
        }
        if (bankItemsN[i] < 1) {
            bankItems[i] = 0;
        }
        outStream.writeWordBigEndianA(pairs.getKey()); // itemID
    }

当前错误

.\src\client.java:75: cannot find symbol
symbol  : class Iterator
location: class client
                Iterator it = bankSearch.entrySet().iterator();
                ^
.\src\client.java:77: java.util.HashMap.Entry is not public in java.util.HashMap
; cannot be accessed from outside package
                        HashMap.Entry pairs = (HashMap.Entry)it.next();
                               ^
.\src\client.java:77: java.util.HashMap.Entry is not public in java.util.HashMap
; cannot be accessed from outside package
                        HashMap.Entry pairs = (HashMap.Entry)it.next();
                                                      ^
3 errors
Press any key to continue . . .

1 个答案:

答案 0 :(得分:9)

您获得的错误归因于:

  • 您没有导入java.util.Iterator

  • HashMap.Entry是一个私人内部类。您应该使用Map.Entry

另外,您应该像templatetypedef所说的那样使用Iterator的通用版本,或者使用for-each构造。

<强>附录

以下是一些实际代码,展示了两种方法:

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

public class MapExample {
    public static void main(String[] args) {
        Map<String, Integer> m = new HashMap<String, Integer>();
        m.put("One", 1);
        m.put("Two", 2);
        m.put("Three", 3);

        // Using a for-each
        for (Map.Entry<String, Integer> e: m.entrySet()) {
            System.out.println(e.getKey() + " => " + e.getValue());
        }

        // Using an iterator
        Iterator<Map.Entry<String, Integer>> it = m.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry e = (Map.Entry<String, Integer>)it.next();
            System.out.println(e.getKey() + " => " + e.getValue());
        }
    }
}