Solved Removing Key from Map

Discussion in 'Spigot Plugin Development' started by TheFl4me, Aug 18, 2018.

  1. quick
    Code (Java):
    if (this.ranks.containsKey(uuid)) this.ranks.remove(uuid);
    question:

    if I try to remove a Key which does NOT exist from a Map by simply using Map.remove(key) will I get a NullpointerException? or do I have to do a Map.ContainsKey(key) check before attempting to remove the key?

    I am asking because IntelliJ is highlighting the containkey function and says it is irrelevant.

    I am currently unable to compile the plugin and test this myself which is why i am asking here, and would appreciate a quick easy answer (I assume this is an easy question). thx
     
  2. You can always read the documentation of Map::remove(K)
     
  3. I did, although the way I understood it it didn't give me a definite answer.

    "Removes the mapping for a key from this map if it is present (optional operation). More formally, if this map contains a mapping from key k to value v such that (key==null ? k==null : key.equals(k)), that mapping is removed. (The map can contain at most one such mapping.)"

    What is ment by "(optional operation)"?
    It clearly says that it will remove the key from the map "if it is present", but what if it isn't? will a NullPointer be thrown?
     
  4. It would tell you that it throws a NPE if the key doesn't exist. As it doesn't, you can just assume it's fine :p
     
  5. No, NPEs are thrown if you are using the dot operator on a null object.

    That means that you can check if the key exists before removing. That's optional because the method will return null if the key doesn't exist.