今天对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对象。