Easiest way to do null checks?

Discussion in 'Plugin Development' started by kyle1320, Aug 13, 2012.

Thread Status:
Not open for further replies.
  1. Offline

    kyle1320

    I'm fairly new to this, and was told that you always need to check for nulls when they're a possibility, or things can go wrong. For me this usually happens while using hashmaps. As-is I am just using nested if statements. For example:
    Code:
    if(myHash.get(hashKey) != null){
        if(myHash.get(hashKey) == 0){
            //do something
        }
    }
    What is the easiest way to do this? Thanks
     
  2. Offline

    Timr

    With HashMaps, you can do something like this:

    Code:
    if(myHash.containsKey(key)) {
        if(myHash.get(key) == 0) {
            System.out.println("Hey, the key's value is 0!!!111oneone");
        }
    }
    I use this with most things I do when working with HashMaps.
     
  3. Offline

    kyle1320

    Ah right, forgot about containsKey(). Is there an easy way to do it with other variables and such?
     
  4. Offline

    Timr

    What sort of variables are you looking at performing null checks on? They're not required in a whole lot of places.
     
  5. Offline

    kyle1320


    Nothing other than hashmaps at this point, just wanted to be prepared in the future. Are they required before checking anything that could be null? For example, if I wanted to check the value of a Player variable but it was null, would that be a problem?
     
  6. Offline

    Courier

    Basically, you can't access methods and fields of a null.
    Code:java
    1. //you CANNOT do this
    2. null.equals("testString");
    3. //but you can do this
    4. "testString".equals(null);

    If there is a chance that something might be null, you need to check before trying to use any of its methods and fields. Using instanceof automatically (essentially) does a null check, so this sort of thing is always safe:
    Code:java
    1. Entity ent = someUnknownMethod();
    2. if(ent instanceof Player)
    3. {
    4. //if ent is null, this will not happen
    5. ((Player)ent).setHealth(0);
    6. }
     
Thread Status:
Not open for further replies.

Share This Page