Cannot get content from HashMap in Java/Bukkit

36 Views Asked by At
public HashMap<Player, Boolean> running = new HashMap<>();

public void load(Player player){
  running.put(player, true);
}

@Eventhandler
public void onInteract(PlayerInteractEvent event){
  if(!running.get(player)) return;
  //More stuff happening here
}

I run the "load"-method at the start of my main-class, so the "check"-part cannot happen before "load()" is finished. I use the same player for both methods, but I always get an error:

Cannot invoke "java.lang.Boolean.booleanValue()" because the return value of "java.util.Map.get(Object)" is null

I don't know why it's not working, so I'd be very thankful if someone could help me :)

1

There are 1 best solutions below

0
Elikill58 On

You should not use running.get(player) to check if a value exist as it try to get it, but in your case it failed as it's not present.

You have containsKey() that will answer. So, you code will be like that:

@Eventhandler
public void onInteract(PlayerInteractEvent event){
    if(!running.containsKey(player)) return;
}

You can also use method that will automatically manage value as getOrDefault() to get value or get default and so be sure there will always have a valid valid. You can also automatically add then with computeIfAbsent() that can be used like this:

@Eventhandler
public void onInteract(PlayerInteractEvent event){
    if(!running.computeIfAbsent(player, (thisPlayer) -> return shouldItBeTrue(thisPlayer))) return;
}