Reputation: 31
From within my code, I add an entry to a HashMap. Later, when trying to get the element by its key, it returns null.
Can't post images yet, but after debugging this is what it says:
https://i.sstatic.net/vf1bW.png https://i.sstatic.net/NxxEI.png
Please help me solve this really weird error!
EDIT: Since you requested, these are the addEntry() and getEntry() methods and the place in code where they are called:
backgroundActor = new BackgroundActor(new BackgroundGraphicsComponent());
backgroundActors.addEntry(backgroundActor, "Background");
borderActor = new BorderActor(new BorderPhysicsComponent(), new BorderGraphicsComponent());
backgroundActors.addEntry(borderActor, "Border");
@SuppressWarnings("unchecked")
@Override
public T getEntry(String key) {
if (gameObjects.get(key) != null) {
return (T) gameObjects.get(key);
}
else throw new NullPointerException(); // this is where it fails
}
@Override
public void addEntry(T gameObject, String key) {
if (gameObject != null) gameObjects.put(gameObject, key);
else throw new NullPointerException();
}
EDIT2: Solved. The problem was with the put() method of HashMap
that takes as its first argument the key and then the value.
Thanks to Nizil and user1498360!
Upvotes: 0
Views: 2490
Reputation: 21
Please change:
if (gameObject != null) gameObjects.put(gameObject, key);
to:
if (gameObject != null) gameObjects.put(key, gameObject);
I hope this will solve your problem.
Upvotes: 1
Reputation: 5140
The put
method of Map
take as first argument the key, then the value.
So in your addEntry
method, you should do:
gameObjects.put(key, gameObject);
Instead of
gameObjects.put(gameObject, key);
This explain why your debugger print {BackgroundActor=Background, BorderActor=Border}
instead of {Background=BackgroundActor, Border=BorderActor}
Upvotes: 4