What's the best way to get something in a list/map etc..

Discussion in 'Spigot Plugin Development' started by FrozenLegend, Jun 7, 2018.

  1. Hi

    I'm wondering what is the best way to get something in a list/map etc..
    Is it better to use #contains or just use #get and use a null check for checking if the value exist

    Sample:

    That's my map storing Object using a String as key
    Code (Text):
    HashMap<String, Object> myMap = new HashMap<>();
    The first way:
    Code (Text):
    if (myMap.containsKey("first")) {
        Object obj = myMap.get("first");
        // Do something with the result
    }
    The second way:
    Code (Text):
    Object obj = myMap.get("first");
    if (obj != null) {
        // Do something with the result
    }
    Thanks !
     
  2. get, getOrDefault, or any of the compute/merge methods. You'd hardly use containsKey.

    Also, use Map as the left hand type. You should always program against the interface or abstract type when possible.
     
  3. Thanks for your reply that's what I thought, but:
    Why ? :unsure:
     
  4. Maintainability, Liskov Substitution Principle.
     
    • Useful Useful x 1
  5. OK thanks, that's good to know :)
     
  6. Just think about it. Would you rather do 2 lookups (contains then get) or 1 (get)? ;)
     
    • Like Like x 1
    • Useful Useful x 1