Usman Mutawakil
Usman Mutawakil

Reputation: 5259

HashMap putAll not adding any elements

Problem

If I explicitly loop through every element in hash map A and "put" each element in hash map B then I have no problem. But if try calling A.putAll(B) for some reason B ends up null.

The code that is working is the basic iterator approach show below:

    Iterator it = A.entrySet().iterator();
    while(it.hasNext()){
        Map.Entry entry = (Map.Entry) it.next();
        B.put((Integer)entry.getKey(),(Integer)entry.getKey());
    }

Where I run into trouble is when I do this.

HashMap A = loadHashMapWithData();
HashMap B = new HashMap();
A.putAll(B);
System.out.println(A);
System.out.println(B);

The second hashmap I am trying to pass data into always ends up "null". Going forward I am using the 1st approach but it would be nice to know why putAll is failing.

Upvotes: 0

Views: 2386

Answers (1)

Zim-Zam O'Pootertoot
Zim-Zam O'Pootertoot

Reputation: 18148

A.putAll(B) is putting all of the elements from B into A - I think you want B.putAll(A) which puts all of the elements from A into B

object.method(parameter) calls method on object passing in parameter - you want to call putAll on B, so B is your object

Upvotes: 3

Related Questions