我正在查看 API 代码,我在 JAVA Api 中找到了这个
java.io.FilePermission.getMask(String actions) {
int mask = NONE;
// Null action valid?
if (actions == null) {
return mask;
}
// Check against use of constants (used heavily within the JDK)
if (actions == SecurityConstants.FILE_READ_ACTION) {
return READ;
} else if (actions == SecurityConstants.FILE_WRITE_ACTION) {
return WRITE;
} else if (actions == SecurityConstants.FILE_EXECUTE_ACTION) {
return EXECUTE;
} else if (actions == SecurityConstants.FILE_DELETE_ACTION) {
return DELETE;
} else if (actions == SecurityConstants.FILE_READLINK_ACTION) {
return READLINK;
}
....
....
.....
}
谁能告诉我为什么他们使用“==”运算符而不是 .equlas() 方法。 :?
最佳答案
这是因为字符串实习。发生的事情是编译器在编译时将 String literals 保留在内存中(这样做是为了节省内存)。当您将字符串文字与 ==
进行比较时,它会起作用,因为它们位于相同的内存位置。
我建议您阅读 this answer ,所以你明白了。这是示例(来自那个答案)及其解释(我的):
1 // These two have the same value
2 new String("test").equals("test") --> true
3
4 // ... but they are not the same object
5 new String("test") == "test" --> false
6
7 // ... neither are these
8 new String("test") == new String("test") --> false
9
10 // ... but these are because literals are interned by
11 // the compiler and thus refer to the same object
12 "test" == "test" --> true
13
14 // concatenation of string literals happens at compile time,
15 // also resulting in the same object
16 "test" == "te" + "st" --> true
17
18 // but .substring() is invoked at runtime, generating distinct objects
19 "test" == "!test".substring(1) --> false
解释:
Why does line 12 and 16 evaluate to true? Because of
String
interning. What happens in these cases is that the compiler internsString
literals in memory at compile time (this is done to save memory). In line 12 and 16 theString
literals that are beign compared are in the same memory location, so the comparison with==
operator returnstrue
. However, this is not recommended unless you want better performance (comparing memory addresses is a lot “cheaper” than a loop) and you are sure that theString
s being compared are interned literals.
关于java - 在 JAVA API 中,为什么使用 '==' 而不是 String.equals() 方法进行相等性检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22293666/