keySet field in HashMap is null

16,895

What do you mean by keySet, entrySet and values? If you mean the internal fields of HashMap, then you should not look at them and need not care about them. They are used for caching.

For example in the Java 6 VM that I use keySet() is implemented like this:

public Set<K> keySet() {
    Set<K> ks = keySet;
    return (ks != null ? ks : (keySet = new KeySet()));
}

So the fact that keySet is null is irrelevant. keySet() (the method) will never return null.

The same is true for entrySet() and values().

Share:
16,895
Mathieu L
Author by

Mathieu L

Updated on July 24, 2022

Comments

  • Mathieu L
    Mathieu L almost 2 years

    I am trying to loop over a HashMap with the keySet() method as below:

    for (String key : bundle.keySet()) {
        String value = bundle.get(key);
        ...
    }
    

    I use a lot of for-each loops on HashMaps in other parts of my code, but this one as a weird behavior: its size is 7 (what's normal) but keySet, entrySet and values are null (according to the Eclipse debugger)!

    The "bundle" variable is instantiated and populated as follows (nothing original...):

    Map <String, String> privVar;
    Constructor(){
        privVar = new HashMap<String, String>();
    }
    public void add(String key, String value) {
        this.privVar.put(key, value);
    }
    
  • Personman
    Personman almost 14 years
    It looks like the Eclipse debugger does display the desired information in the 'table' field.
  • tricknology
    tricknology almost 11 years
    It is returning null for me in Java 7 using data.keySet().toArray(); where data is a HashMap<String,String> and it is not null
  • Joachim Sauer
    Joachim Sauer almost 11 years
    @tricknology: if that's the case, I suggest you post it as a new question (ideally with a SSCCE).