java String 的值传递问题

今天对String类的值传递问题进行一番研究,终于明白是为什么了。

之前一直听说String是一个比较特殊类,String在作为方法的实参传递的是值,而不是引用。但是为什么会这样?这就要从String的源码来分析了。


public String(String original) {
	int size = original.count;
	char[] originalValue = original.value;
	char[] v;
  	if (originalValue.length > size) {
 	    // The array representing the String is bigger than the new
 	    // String itself.  Perhaps this constructor is being called
 	    // in order to trim the baggage, so make a copy of the array.
            int off = original.offset;
            v = Arrays.copyOfRange(originalValue, off, off+size);
 	} else {
 	    // The array representing the String is the same
 	    // size as the String, so no point in making a copy.
	    v = originalValue;
 	}
	this.offset = 0;
	this.count = size;
	this.value = v;
    }
this.value就是存放的我们的字符串。但是这个this.value 是什么样的成员变量呢?接着往下看

 /** The value is used for character storage. */
   <span style="background-color: rgb(255, 255, 102);"> private final char value[];</span>

    /** The offset is the first index of the storage that is used. */
    private final int offset;

    /** The count is the number of characters in the String. */
    private final int count;

    /** Cache the hash code for the string */
    private int hash; // Default to 0

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = -6849794470754667710L;
“final”就是这个罪魁祸首导致了String的值一旦被初始化就不能再改变了!所以我猜测String作为实参传递仍然是引用。只是在方法内部改变String类型形参的值时,并不是把原来的String对象的value改变了,而是又重新new了一个新的String对象。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值