Why is myString.equals(“aString”); different from “aString”.equals(myString);?

前端 未结 3 1512
我在风中等你
我在风中等你 2020-12-19 05:39

I heard several times that in using boolean equals(Object o) to compare Strings, it\'s better to put the constant on the left side of the function

3条回答
  •  不思量自难忘°
    2020-12-19 06:22

    Because if myString is null you get an exception. You know "aString" will never be null, so you can avoid that problem.

    Often you'll see libraries that use nullSafeEquals(myString,"aString"); everywhere to avoid exactly that (since most times you compare objects, they aren't generated by the compiler!)

提交回复
热议问题