Kod*_*aga 3 java string equals
我正在探索在equals方法内部遇到的Java中的String API
首先,
if (anObject instanceof String) {
String anotherString = (String)anObject;
Run Code Online (Sandbox Code Playgroud)
即使在检查instanceOf String是否存在已在该条件内进行类型转换的对象之后,也请您帮我理解一下。
其次,
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length)
Run Code Online (Sandbox Code Playgroud)
这是为什么我们anotherString.value.length不使用anotherString.length
我试着像多个来源JLS,Herbert Schildt图书,但无法真正解密此。请帮助我更好地理解这一点。
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
即使在检查instanceOf String是否存在已在该条件内进行类型转换的对象之后,也请您帮我理解一下。
Regardless of the instanceof check, you can't assign a value with type Object to a variable of type String. So anObject has to be typecast to assure the compiler that it's okay. (There is at least one language — TypeScript — whose compiler would be able to infer that the assignment was okay based on the instanceof check, but Java's compiler doesn't do that...yet.)
Here why are we using anotherString.value.length not anotherString.length
value is the instance member within the String object containing the actual string data (as a char[] or byte[] array; it was char[] in JDK 1-8, it's byte[] in JDK 9+). It makes sense to use value.length because that's the length of the array; if the values of the two strings aren't the same length, they can't be equal. To use anotherString.length() would require a pointless method call (remember, the public length is a method, not a field), which would just end up looking at value.length anyway (plus some overhead, at least in JDK11).