Java equals() ordering

后端 未结 6 913
执念已碎
执念已碎 2021-01-12 02:55

If I try to do a .equals() on a null string in java, a null pointer exception will be thrown. I am wondering, if I am trying to compare if a string is equal to

6条回答
  •  孤街浪徒
    2021-01-12 03:34

    I would keep the "CONSTANT.equals(possibleNull)" code without the null test only if it is a normal condition that the variable could be null - for instance because it just came out of a property map.

    Similarly you can get away with not checking for null in instanceof-checks - like:

    Food dinner = map.get("dinner");
    if (dinner instanceof Soup) {
          ((Soup)blah).eat();
    }  // We don't care if it is a Fish or null
    

    But if you really did not expect null, you should explicitly check for that in a separate if-test, and handle it appropriately. It's generally better to catch such data errors early rather than later.

提交回复
热议问题