为什么 Java 在 equalsIgnoreCase 方法中比较 (this == another String) 以检查不敏感的字符串?
另外,String equals 是比较(this == another String)来比较两个对象?
Java 6:下面给出了 String 类 equalsIgnoreCase 实现。
public boolean equalsIgnoreCase(String anotherString) {
return (this == anotherString) ? true :
(anotherString != null) && (anotherString.count == count) &&
regionMatches(true, 0, anotherString, 0, count);
}
Java 6:String 类等于下面给出的实现。
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
最佳答案
Why Java is comparing (this == another String) inside equalsIgnoreCase method for checking a string insensitive?
这是一个优化。如果传入的引用与 this
完全相同,则 equals
必须 返回 true
,但我们不不需要查看任何字段等。一切都和它自己一样。来自 Object.equals(Object)
的文档:
The equals method implements an equivalence relation on non-null object references:
- It is reflexive: for any non-null reference value x, x.equals(x) should return true.
- ...
平等检查开始于:
- 其他引用是否等于
this
?如果是,则返回 true。 - 另一个引用是否为空?如果是,则返回 false。
- 其他引用是否引用了错误类型的对象?如果是,则返回 false。
然后您继续进行特定于类型的检查。
关于java - 为什么String.equals里面有一个 "=="?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31041936/