今天看到字符串的append方法返回的新对象不改变内存地址,特意看了看源码
首先是测试代码
public class stringbufferapp {
public static void main(String[] args){
StringBuilder str = new StringBuilder("abcde"); //默认分配(总长+16)的大小
System.out.println(str.hashCode());
str.append("abcjioasjdioajfakljg;lkag");
System.out.println(str.hashCode());
}
}
输出结果:
460141958
460141958
进入StringBuilder类的append方法:
@Override
public StringBuilder append(String str) {
super.append(str);
return this;
}
进入父类AbstractStringBuilder的append方法:
public AbstractStringBuilder append(String str) { //传入添加的append的字符串
if (str == null) //字符串的判断
return appendNull();
int len = str.length(); //append的字符串长度
ensureCapacityInternal(count + len); //@1 调用方法判断长度是否超了 count+len=总长
str.getChars(0, len, value, count); //@2
count += len; //count=新字符串长度
return this;
}
@1
private void ensureCapacityInternal(int minimumCapacity) {
if (minimumCapacity - value.length > 0) { //判断是否超过当前长度
value = Arrays.copyOf(value,newCapacity(minimumCapacity)); //复制当前数组到新value数组中,newCapacity()返回新长度,
}
}
@2
getChar()方法调用了
System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);函数,
**
//源头找到了,下面为该方法的注释,规定了返回相同的HASHCODE,所以返回的地址相同,系统方法,看不到函数体
**
- Returns the same hash code for the given object as
- would be returned by the default method hashCode(),
- whether or not the given object’s class overrides
- hashCode().
- The hash code for the null reference is zero.