String方法返回的String对象 - java

ana*_*ema -5 java string

如果在字符串常量池中添加了字符串文字,并且每个String方法都在创建一个新的String对象,那么这意味着这些方法返回的String对象是否被添加到常量池中?

"String".replace('g','G') == "String".replace('g','G')
Run Code Online (Sandbox Code Playgroud)

上面的代码打印为false,即使替换的结果是"StrinG",因为replace方法返回一个新的String对象,然后它恰好发生"=="的两边都是不同的String对象碰巧具有相同的字符顺序是"StrinG"?

**编辑:**由Pshemo评论,是的,我确实知道"=="和"等于()"之间的区别,问题是如果任何机会,方法输出的字符串也被添加到恒定的池.

Kar*_*oly 5

来自替换文档:

返回一个新字符串,该字符串是使用newChar替换此字符串中出现的所有oldChar.

原始源代码:

public String replace(char oldChar, char newChar) {
    if (oldChar != newChar) {
        int len = count;
        int i = -1;
        char[] val = value; /* avoid getfield opcode */
        int off = offset;   /* avoid getfield opcode */

        while (++i < len) {
            if (val[off + i] == oldChar) {
                break;
            }
        }
        if (i < len) {
            char buf[] = new char[len];
            for (int j = 0 ; j < i ; j++) {
                buf[j] = val[off+j];
            }
            while (i < len) {
                char c = val[off + i];
                buf[i] = (c == oldChar) ? newChar : c;
                i++;
            }
            return new String(0, len, buf);
        }
    }
    return this;
}`
Run Code Online (Sandbox Code Playgroud)

我知道,String是不可变的,我们有一个很酷的字符串池,但在这种情况下我们有两个强引用,我的意思是两个相同字符串的NEW实例.由于我们有两个新实例,这意味着我们有两个不同的内存地址.

来源:http://grepcode.com/file_/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/String.java/?v = source

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace(char,%20char)