Java equals() ordering

后端 未结 6 911
执念已碎
执念已碎 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:29

    If you are concerned about the quality of your code, write a helper class that takes care of equality test:

    public class ObjectHelper {
        public static boolean testEquality(Object o1, Object o2) {
            if (o1 == null && o2 == null) return true;
            if (o1 == null) return false;
            return o1.equalts(o2);
        }
    }
    

    Then use it like this:

    if (ObjectHelper.testEquality(aStringVariable, My_CONSTANT_STRING))
    

    Your so-called constant MIGHT stop being constant. It might be read from a configuration file some time in the future.

提交回复
热议问题