java - 在 JAVA API 中,为什么使用 '==' 而不是 String.equals() 方法进行相等性检查

标签 java string

我正在查看 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 interns String literals in memory at compile time (this is done to save memory). In line 12 and 16 the Stringliterals that are beign compared are in the same memory location, so the comparison with == operator returns true. 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 the Strings being compared are interned literals.

记住 those SecurityConstants are strings.

关于java - 在 JAVA API 中,为什么使用 '==' 而不是 String.equals() 方法进行相等性检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22293666/

相关文章:

java - 在没有嵌入 pig 脚本的情况下在 java 中运行 pig

java - 删除一行数据后无法刷新TableView

java - 什么是 OutputStreamWriter 的逆函数

java - 如何从Java中的单词中删除重复的字母

c++在子字符串的最后一个匹配之后删除子字符串

Java 字符串 - 1 不是 1?

java - 了解手机何时在 Android 设备上进入建筑物

java - 使用 Java 注释处理器生成文档/XML 的实际示例

c# - 在 C# 中,从字符串中解析出此值的最佳方法是什么?

java - contains方法如何匹配?