为什么是myString.equals(" aString");不同于“aString”.equals(myString);? [英] Why is myString.equals("aString"); different from "aString".equals(myString);?
问题描述
我多次使用 boolean equals(Object o)
来比较 Strings
,最好放一下函数左侧的常量如下所示:
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:
- 错误:myString.equals(aString);
- 好:aString.equals(myString);
为什么会这样?
推荐答案
因为如果 myString
为null,则会出现异常。你知道aString
永远不会为空,所以你可以避免这个问题。
Because if myString
is null you get an exception. You know "aString"
will never be null, so you can avoid that problem.
你经常会看到使用 nullSafeEquals(myString,aString);
的库到处都是为了避免这种情况(因为大多数时候你比较对象,它们不是由编译器生成的!)
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!)
这篇关于为什么是myString.equals(" aString");不同于“aString”.equals(myString);?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!