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

2019-01-26 09: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 as in the following:

  • Bad: myString.equals("aString");
  • Good: "aString".equals(myString);

Why is this?

3条回答
ら.Afraid
2楼-- · 2019-01-26 10:26

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!)

查看更多
在下西门庆
3楼-- · 2019-01-26 10:30

This is a defensive technique to protect against NullPointerExceptions. If your constant is always on the left, no chance you will get a NPE on that equals call.

查看更多
叼着烟拽天下
4楼-- · 2019-01-26 10:32

This is poor design, because you are hiding NullPointerExceptions. Instead of being alerted that string is null, you will instead get some weird program behaviour and an exception being thrown somewhere else.

But that all depends if 'null' is a valid state for your string. In general 'null's should never be considered a reasonable object state for passing around.

查看更多
登录 后发表回答