java - String.intern() 是否更改原始字符串 JDK7 的引用

标签 java string

<分区>

Possible Duplicate:
intern() behaving differently in Java 6 and Java 7

在为 this question 做例子时

当我在 String 上调用 intern() 方法时,我注意到 intern() 方法有一个奇怪的行为,此后我可以使用 == 原始字符串的运算符。

intern() 方法的 JavaDoc:

Returns a canonical representation for the string object. A pool of strings, initially empty, is maintained privately by the class String.

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

上面的 Javadoc 并没有说 原始字符串 被改变了。那么为什么这个程序在输入 test 时打印 okay

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner user_input = new Scanner(System.in);
        String username;
        System.out.print("username: ");
        username = user_input.next();
        // Even if I do not assign returned string for comparison still it compares
        // okay else it does not compare
        username.intern();
        if (username == "test") {
            System.out.println("okay");
        }
        else {
            System.out.println("not okay");
        }
    }
}

最佳答案

String.intern() 返回 intern()ed 字符串。这是因为方法无法更改传递给它的引用。

So why this program prints okay when test is the input.

它打印正常,因为 intern()ed 字符串是第一次看到此字符串,因此它成为“测试”的一个字符串文字。改变的不是字符串,而是用于“测试”的对象。

试试吧。

String te = "te", st = "st";
// "test".length();
String username = te + st;
username.intern();
System.out.println("String object the same is: "+ (username == "test"));

在这种情况下,Java 7 update 7 中的输出是

String object the same is: test

但在 Java 6 update 32 上运行它或取消注释该行,以便首先看到“test”,然后你就可以了。

String object the same is: false

关于java - String.intern() 是否更改原始字符串 JDK7 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12275677/

相关文章:

正则表达式匹配特定字符的确切数量

c - 如何从c中的较大字符串中获取子字符串?

string - 如何使用多个字符的字符串在 PowerShell 中 "split"字符串?

c - 数组已填充最后一个元素

java - 使用嵌套迭代器迭代两级结构

java - 实现滑动窗口(java)

java - 检查 youtube-api 中视频对象中是否存在嵌套键以避免 NULLPOINTEREXCEPTION

java - 从 forEach 循环内部传播异常

java - 从 VB.Net 执行 Java 类

javascript - 字符串中的字符串不能被换行符分割