Can't see the contents of the HashMap

谁说胖子不能爱 提交于 2019-12-13 03:20:51

问题


Output reaches flag2 but I can't see what is inside the HashMap. The code is:

public class traffic_analysis {


static HashMap<InetAddress,Integer> mp=new HashMap<InetAddress, Integer>();


    static void SrcCnt(InetAddress src_ip) {
        InetAddress SourceIP = src_ip;
        System.out.println(SourceIP);

        if (mp.get(SourceIP) == null){
            mp.put(SourceIP, 0);
            System.out.println("----MPIKE----");
        }else {
            mp.put(SourceIP,mp.get(SourceIP)+1);
            System.out.println("----MPIKE XANA----");
        }

        System.out.println(mp.toString());
    }


static void PrintMap() {
    System.out.println("----EIMAI EDW----");

    Iterator iterator = mp.keySet().iterator();

    while (iterator.hasNext()) {
         System.out.println("----flag----");
       String key = iterator.next().toString();
       System.out.println("----flag2----");
       String value = mp.get(key).toString();
       System.out.println("----flag3----");

       System.out.println(key + "blabla " + value);
    }
}


}

Where is the problem?


回答1:


You're calling toString on the actual key. When you try to get it with the string, that will fail. Try this instead:

InetAddress key = iterator.next();
System.out.println("----flag2----");
String value = mp.get(key).toString();
System.out.println("----flag3----");



回答2:


The toString() method of an object doesn't do the same thing as casting the object to a String.

What about String key = iterator.next() rather than String key = iterator.next().toString() ?



来源:https://stackoverflow.com/questions/6036413/cant-see-the-contents-of-the-hashmap

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