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

为君一笑 提交于 2019-11-28 03:43:41

问题


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?


回答1:


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




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/7577089/why-is-mystring-equalsastring-different-from-astring-equalsmystring

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!