4

I'm reading a data.ser file to fill some HashMaps with saved data.

Although the Map has the values I'm supposed to have, the KeySet, EntrySet, and values are all null. for example, Hashmap "Employees" looks like this when I inspect it in debug mode:

hashmap as shown with debugs inspect option:

Can someone help me figure out what's wrong with it? How is that situation even possible?

An example for a null value returned although the map contains a value (Employee) with the key (ID) im searching: problem example

Roi811
  • 67
  • 1
  • 6
  • Why are you interested in these internal fields? The HashMap correctly behaves if you use its public methods, am i right? – WonderCsabo Aug 27 '14 at 21:30
  • If i try to search the map by a given key it always returns null because keySet is null. i think. – Roi811 Aug 27 '14 at 21:34
  • 1
    @Roi811 It won't return null if the underlying Map (stored in the `m` member) contains that key. – Eran Aug 27 '14 at 21:35
  • I doubt it. The `Map` returns null because either the key is not present or the value for the key is indeed `null`. – WonderCsabo Aug 27 '14 at 21:36
  • @Roi811 You'll get more effective help if you post the actual problem you are having (_If i try to search the map by a given key it always returns null_, and elabolate/give examples), versus only showing a small part of what you looked into. – tobii Aug 27 '14 at 21:39
  • @tobii You are right. added an example to the post. – Roi811 Aug 27 '14 at 21:47

1 Answers1

4

It's an UnmodifiableMap.

The data members you mentioned are initialized to null :

private transient Set<K> keySet = null;
private transient Set<Map.Entry<K,V>> entrySet = null;
private transient Collection<V> values = null;

The methods of the same names access the underlying Map to return the non-null values and cache them in those variables the first time they are called.

public Set<K> keySet() {
    if (keySet==null)
    keySet = unmodifiableSet(m.keySet());
    return keySet;
}

public Set<Map.Entry<K,V>> entrySet() {
    if (entrySet==null)
    entrySet = new UnmodifiableEntrySet<K,V>(m.entrySet());
    return entrySet;
}

public Collection<V> values() {
    if (values==null)
    values = unmodifiableCollection(m.values());
    return values;
}

Therefore, if you'll call these three methods, you'll see that those data members are no longer null.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • **Thank you for your answer**. I'm having a hard time trying to figure out where is the proper place to put those methods. Reason being, i have a prepared java program and i'm supose to write a suitable GUI for it. More over, there are multiple HashMap's that serves as the DB of this program that are declared in the "view" class. Getters indeed send an UnmodifiableMap of these maps as you mentioned. – Roi811 Aug 27 '14 at 22:07