Can't see the contents of the HashMap

2019-08-27 07:25发布

问题:

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() ?



标签: java hashmap