concat method of the String class in Java

Before looking at concat (), you first need to be clear that two of the special nature of String.

  • Length immutable
  • Immutable values 
    of these two points of String statement can be reflected from the source code:
  private final char[] value ;
  • 1

Wherein the characteristic corresponds unchangeable final value; and char [] String corresponding to the characteristic length is unchangeable.

Therefore, when we splicing String, it should produce a new string. 
For this, we can be the source of interpretation of the concat () reached the same conclusion.

@param  str 需要拼接到原字符串的新串
@param  otherlen 新串的长度
@param  len 原字符串的长度
@param  buf 存放最终字符串的字符数组(长度为len+otherlen)
@method copyOf(char[] original, int newLength) 复制指定的数组,截取或用 null 字符填充(如有必要),以使副本具有指定的长度。 @method getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) 将字符从此字符串复制到目标字符数组。 public String concat(String str) { int otherLen = str.length(); if (otherLen == 0) { return this; } int len = value.length; char buf[] = Arrays.copyOf(value, len + otherLen); str.getChars(buf, len); return new String(buf, true); }

Source analysis:

concat()方法首先获取拼接字符串的长度,判断这个字符串长度是否为0(判断这个用来拼接的字符串是不是空串),如果是就返回原来的字符串(等于没有拼接);否则就获取源字符串的长度,创建一个新的char[]字符数组,这个字符数组的长度是拼接字符串的长度与源字符串的长度之和,通过Arrays类的copyOf方法复制源数组,然后通过getChars方法将拼接字符串拼接到源字符串中,然后将新串返回。
  • 1

API also this method is explained:

  • If the string length parameter is 0, this String object is returned.
  • Otherwise, create a new String object that represents the sequence of characters and character sequences character sequence parameter string String object represents thus represented connected together.

In summary, when a String object stitching, creates a new string to store the new string.

Guess you like

Origin www.cnblogs.com/zhuyeshen/p/12132213.html