String concatenation in various ways

1. Reason: When I was in the company, string splicing was used in the self-developed framework, so I want to make a brief summary of various ways of string splicing

2. Method 1: Use + sign stitching (least recommended)

A char array is an array of constants that are not mutable and are stored in a pool of constants in the JVM. Because of the overloading of the + operator (C ++ content), it creates a StringBuilder object every time it is concatenated. The StringBuilder object is concatenated with its append(Stirng STR). New String(StringBuilder) creates a String object. However, such frequent object creation is a performance drag, so the use of + signs for concatenation is not recommended.

3. Option 2: concatenate using Concat functions

① Code examples

String strA = "Hello"; String strB = "world"; String concat = strA.concat(",").concat(strB); System.out.println(concat); // The result is hello, world

(2) the underlying source call function graph

(3) Horizontal call to the underlying source parsing (copy the original String value)

Public String concat(String STR) {// If we add an empty String, we return int otherLen = str.length(); if (otherLen == 0) { return this; } int len = value.length; char buf[] = Arrays.copyOf(value, len + otherLen); / / copy of the original String to a new buf array -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the above is the transverse, longitudinal / / here is copy of STR is added to the new buf array STR. GetChars (buf, len); return new String(buf, true); } public static char[] copyOf(char[] original, original, original, original, original, original, original, original, original, original, original, original, original, original int newLength) { char[] copy = new char[newLength]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; }

(4) the underlying source parsing System. ArrayCopy (array control, more flexible than copyOf)

  • A one-dimensional array tests whether System. arrayCopy is the same storage space

    char[] one_char1 = new char[]{'a','b','c'}; char[] one_char2 = new char[5]; // Copy the values from index 1 to index 2 (length 2) in one_char1 to index 3 and index 4 in one_char2; The leading index of the contents copied from the source array; // copy the array; The copy array places the leading index of the content to be copied; Note: ① Three of the numeric parameters cannot be negative; ArrayCopy (one_char1,1,one_char2,3,2); arrayCopy (one_char1,1,one_char2,3,2); arrayCopy (one_char1,1,one_char2,3,2); for(char value:one_char2){ System.out.println("value2="+value); System.out.println(); } // Test whether changing the value of one_char[2] will change the value of one_char[1]; for(char value:one_char1){ System.out.println("value1="+value); } //one_char1 returns a, b, c; One_char [1] is not changed by the change in one_char2, which means that the two arrays are not the same storage address, which is known as shallow copy, or value passing
  • A 2-D array tests whether System. ArrayCopy is the same storage space

    char[][] two_char1 = new char[][]{{'a','b','c'},{'e','f','g'},{'h','i','j'}}; char[][] two_char2 = new char[3][5]; // For example: copy lines 1 through 2 from two_char1 into line 1 of two_char2; If there are not enough rows, then store to the next line // copied array; The index of the number of lines copied from the source array; // copy the array; A copy array holds the index of the number of rows in which the content is copied. Note: ① Three of the numeric parameters cannot be negative; ArrayCopy (two_char1,0,two_char2,1,2); for(char[] one_Array:two_char2){ for(char value:one_Array){ System.out.println("value2="+value); } two_char2[0][0] = 't'; for(char[] one_Array:two_char1){ for(char value:one_Array){ System.out.println("value2="+value); }} // Change the value of two_char2, and the value of two_char1 will also change // Change the value of two_char1, and the value of two_char2 will change accordingly, which means that they are the same storage space, which is called deep copy, or address passing

    Vertical calls to underlying source parsing (copy the value of XXX in concat(XXX))

    Public String concat(String STR) {// If we add an empty String, we return int otherLen = str.length(); if (otherLen == 0) { return this; } int len = value.length; char buf[] = Arrays.copyOf(value, len + otherLen); -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the above is the transverse, longitudinal STR. Below is the getChars (buf, len); GetChars return new String(buf, true); } // void getChars(char DST [], int dstBegin) {// System.arrayCopy (value, 0, DST, dstBegin, value.length); }

    3. Option 3: Stitch using StringBuilder

    ① Code examples

    StringBuilder strA = new StringBuilder("hello,"); strA.append("world"); System.out.println(strA); // The result is hello,world

    (2) the underlying source call function graph

    ③ source code parsing

    public StringBuilder append(String str) { super.append(str); return this; } //AbstractStringBuilder is the parent class of StringBuilder. Public AbstractStringBuilder Append (String STR) {if (STR == null) return appendNull(); int len = str.length(); // EnsureCapityInternal (count + len); // EnsureCapityInternal (count + len); STR. GetChars (0, len, value, count); STR. ArrayCopy (); count += len; return this; }

    4. Option 4: use StringBuffer concatenation

    StringBuffer concatenation is similar to StringBuilder in that it calls methods in its abstract parent class AbstractStringBuilder, except that the StringBuffer methods use the synchronized keyword

    ② Use scenario: use under the condition that thread safety is required

    5. Method 5: Use StringJoiner for splicing (if the same delimiter is needed for multiple splicing)

    ① Use example 1 (without prefix and suffix)

    StringJoiner sj = new StringJoiner(",","[","]"); sj.add("hello").add("world").add("yangshengyuan"); / / the result for the hello, world, yangshengyuan

    ② Use examples 2 (with prefix and suffix)

    StringJoiner sj = new StringJoiner(",","[","]"); sj.add("hello").add("world").add("yangshengyuan"); / / the result of [hello, world, yangshengyuan]

    ③ source code parsing

    Public StringJoiner add(CharSequence newElement) {prepareBuilder().append(newElement); public StringJoiner add(CharSequence newElement); return this; } / / StringJoiner prepareBuilder method in private StringBuilder prepareBuilder () {/ / value is StringBuilder types, is used to store the data, // If the value is empty, add as a prefix; if the value is empty, add as a prefix; Otherwise, add the delimiter if (value! = null) { value.append(delimiter); } else { value = new StringBuilder().append(prefix); } return value; }

    6. Trigger the code that wrote this article (by reflecting any attribute in the prior class can be spliced with delimiters)

    // Because the whole project is using the ORM framework, it needs a format for the stitching and output, so it is not necessary to change this function every time the model is changed. Therefore, using reflection allows it to do this regardless of the number of attributes you add to the entity class, so the code is robust

    public String getString() throws IllegalArgumentException,     IllegalAccessException {
          StringJoiner sj = new StringJoiner(",");
          Class<ScoreResultmap> srClass = ScoreResultmap.class;
          Field[] fields = srClass.getDeclaredFields();
          for(Field field:fields) {
              String value = String.valueOf(field.get(this));
              sj.add(value);
          }
          return sj.toString();
    }

    7. Conclusion: This paper introduces four different string concatenation methods, usage scenarios and source analysis of them. I’ll give you an overview of the EnsureCapacityInternal method next time, and thank you for taking the time to read this article.