String字符串的concat()方法源码分析
1.java提供了“+”运算符能进行字符串的连接操作。
- API里提供的是:
![API关于字符串连接](https://i-blog.csdnimg.cn/blog_migrate/64068890d87c64f6b32340d0a495b9e3.png)
- 首先,string类型是不可变的,所以,通过StringBuffer或者StringBuilder对象实现了字符串的拼接。通过创建StringBuffer或者StringBuilder对象,然后调用其中的append()方法,得到一个拼接后的StringBuffer或者StringBuilder对象,最后调用toString()方法,返回得到的String对象的地址值。
举例图解:![“+”的字符串连接举例图解](https://i-blog.csdnimg.cn/blog_migrate/e1207273f04f6dd59a14fa79486279e5.png)
2.concat()方法源码分析
public String concat(String str) {
//获取传入字符串的长度
int otherLen = str.length();
//如果传入字符串长度为0,输出原字符串
if (otherLen == 0) {
return this;
}
//获取原字符串的长度
int len = value.length;
//调用Arrays.copyOf()方法,传入原字符串,和原字符串和传入字符串长度之和,返回连接后的字符数组,该数组从0-len包含着原字符串元素
char buf[] = Arrays.copyOf(value, len + otherLen);
//调用getChars()方法,传入扩展后的字符数组和原字符串长度
str.getChars(buf, len);
//根据生成的拼接后的字符数组创建一个新的String对象
return new String(buf, true);
}
public static char[] copyOf(char[] original, int newLength) {
//根据传入的字符串长度之和创建一个新的字符数组
char[] copy = new char[newLength];
//调用arraycopy()方法
//将原数组元素从索引为0的位置开始复制,到另一个数组,从新数组索引为0的位置开始,复制的元素个数为调用Math.min(a,b)方法后得到的长度
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
//返回的字符数组是包含着原字符串元素的扩展后的字符数组
return copy;
}
public static int min(int a, int b) {
//三元表达式判断a和b长度,输出a和b之间的最小值
return (a <= b) ? a : b;
}
void getChars(char dst[], int dstBegin) {
//调用System.arraycopy()方法
//将传入字符串从0的位置开始复制到扩展后的字符串,从原字符串长度的位置开始复制,复制的元素个数为传入字符穿的长度
System.arraycopy(value, 0, dst, dstBegin, value.length);
}