Iterating through a HashMap

时光怂恿深爱的人放手 提交于 2019-12-21 05:51:40

问题


Okay so i'm currently working on a searching method, the terms searched are ran through the database and the matching products are added to a hashMap with 2 Integer fields.

then after the hashmap is made, the items are to be shown, however i'm having trouble getting the hashmap to print out the details

here's my code

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

and the use

    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
    }

current errors

.\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:


The errors you are getting are due to:

  • You did not import java.util.Iterator

  • HashMap.Entry is a private inner class. You should use Map.Entry

Also you should, as templatetypedef says, use the generic version of Iterator, or use a for-each construct.

ADDENDUM

Here is some actual code, demonstrating both approaches:

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());
        }
    }
}


来源:https://stackoverflow.com/questions/7007513/iterating-through-a-hashmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!