Java源码阅读-String,Long

String值的不变性

/** The value is used for character storage. */
private final char value[];

String s="zxk";
s="rust";

这个s变量的值发生了改变吗?

答案是并没有,我们可以翻出源码来看一下

    /** The value is used for character storage. */
    private final char value[];

这个value数组的定义是一个常量的数组,那怎么可能s变量发生改变了嘛?
但是确实s,输出出来的是rust,没错。
在这里插入图片描述
在这里插入图片描述
首先可以看上面两张图,第一张s的对象地址在542,第二张s对象的地址在544,可以看出,s的内容并没有发生改变,只是对象发生了变化,也可以说s不再是当初那个s了。

equals方法

Equals方法写的也很清晰,比较两个字符串。

    /**
     * Compares this string to the specified object.  The result is {@code
     * true} if and only if the argument is not {@code null} and is a {@code
     * String} object that represents the same sequence of characters as this
     * object.
     *
     * @param  anObject
     *         The object to compare this {@code String} against
     *
     * @return  {@code true} if the given object represents a {@code String}
     *          equivalent to this string, {@code false} otherwise
     *
     * @see  #compareTo(String)
     * @see  #equalsIgnoreCase(String)
     */
     //
    public boolean equals(Object anObject) {
    	//引用同一个类型
        if (this == anObject) {
            return true;
        }
        //anObject是否是String类型
        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;
    }
replace
    public String replace(char oldChar, char newChar) {
    	//两个字符是否一致
        if (oldChar != newChar) {
            int len = value.length;
            int i = -1;
            char[] val = value; /* avoid getfield opcode */
			//检测是否有待被替换的字符的第一个位置
            while (++i < len) {
                if (val[i] == oldChar) {
                    break;
                }
            }
            if (i < len) {
                char buf[] = new char[len];
                //直接复制前面那些不用替换的
                for (int j = 0; j < i; j++) {
                    buf[j] = val[j];
                }
                while (i < len) {
                    char c = val[i];
                    //是否是要被替换的字符
                    buf[i] = (c == oldChar) ? newChar : c;
                    i++;
                }
                return new String(buf, true);
            }
        }
        return this;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值