Markus Kreth
Markus Kreth

Reputation: 748

(Hash-)Map has entry, get delivers null

I have no idea what is happening here. I have a HashMap with the following keyset of size 4:

steps.keySet()
(java.util.HashMap$KeySet)
[INIT_FZLIST, INIT_DATA, INSTALL_DATABASE, PROMPT_GERAETEID]

INIT_FZLIST, INIT_DATA, INSTALL_DATABASE and PROMPT_GERAETEID are values of an enum.

Also the entrySet delivers the 4 entries.

steps.entrySet()
(java.util.HashMap$EntrySet)
[INIT_FZLIST=de.ansat.terminal.activity.widgets.PendingCheckbox{b50cb4e0 V.E..... ......I. 24,524-456,666},
 INIT_DATA=de.ansat.terminal.activity.widgets.PendingCheckbox{b50c8748 V.E..... ......I. 24,350-456,524},
 INSTALL_DATABASE=de.ansat.terminal.activity.widgets.PendingCheckbox{b508e288 V.E..... ......I. 24,68-456,209},
 PROMPT_GERAETEID=de.ansat.terminal.activity.widgets.PendingCheckbox{b50c59b0 V.E..... ......I. 24,209-456,350}]

but if I do this:

steps.get(INSTALL_DATABASE)
 null

the map returns null and of cause I get a nullpointerexception if I try to work with the resulting object.

This is running in an Android activity. I'm using Android 4.2.2 on API Level 17

[Edit]

private Map<InstallSteps, PendingCheckbox> steps = new HashMap<InstallSteps, PendingCheckbox>();

is a field of my activity class.

I have several AsyncTasks working on that map, as it represents the progress of an installation process.

PendingCheckbox is a View extending LinearLayout.

[Edit2] steps is filled in onCreate(..) this way:

    PendingCheckbox installDb = new PendingCheckbox(InstallActivity.this);
    installDb.setText(INSTALL_DATABASE);
    installDb.setChecked(false);
    installDb.setLayoutParams(layoutParams);
    root.addView(installDb);
    steps.put(InstallSteps.INSTALL_DATABASE, installDb);

Has anyone an idea what might cause this behaviour? I'm completly stuck. Any tip would be appreciated!

Upvotes: 0

Views: 116

Answers (2)

Joop Eggen
Joop Eggen

Reputation: 109557

Maybe steps is altered before the get, or the puts occur later, or you have two declarations of steps.

Upvotes: 0

AllTooSir
AllTooSir

Reputation: 49372

You can use an EnumMap instead of HashMap.

A specialized Map implementation for use with enum type keys. All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created.

As far as your code is concerned , remember:

  1. The hashCode of the Objects in map should not change once added to map. A good implementation of equals() and hashCode() is required.

  2. Check if you actually put(key,value) an object with that key before get(key)ing its value.

Upvotes: 2

Related Questions