In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is about how Java implements string concatenation. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
01, "+" operator
When it comes to posture, the "+" operator must be the most common type of string concatenation, not one of them.
String chenmo = "Silence"; String wanger = "King II"; System.out.println (chenmo + wanger)
Let's decompile this code using JAD.
String chenmo = "\ u6C89\ u9ED8"; / / Silent String wanger = "\ u738B\ u4E8C"; / / Wang er System.out.println ((new StringBuilder (String.valueOf (chenmo) .append (wanger). ToString ())
I went and replaced the "+" operator with StringBuilder's append method when compiling. In other words, the "+" operator is only a formalism when concatenating strings, making it easier for developers to use, and the code looks simpler and easier to read. It's a kind of grammatical candy of Java.
02 、 StringBuilder
Excluding the "+" operator, StringBuilder's append method is the second commonly used string concatenation pose.
Let's take a look at the source code of the append method of the StringBuilder class:
Public StringBuilder append (String str) {super.append (str); return this;}
There is nothing to see in these three lines of code, but the append method of the parent class AbstractStringBuilder:
Public AbstractStringBuilder append (String str) {if (str = = null) return appendNull (); int len = str.length (); ensureCapacityInternal (count + len); str.getChars (0, len, value, count); count + = len; return this;}
1) determine whether the concatenated string is null, and if so, treat it as the string "null". The source code of the appendNull method is as follows:
Private AbstractStringBuilder appendNull () {int c = count; ensureCapacityInternal (c + 4); final char [] value = this.value; value [C++] = 'nasty; value [C++] =' UFO; value [C++] = 'lump; value [C++] =' lump; count = c; return this;}
2) whether the length of the stitched character array exceeds the current value, and if so, expand and copy it. The source code of the ensureCapacityInternal method is as follows:
Private void ensureCapacityInternal (int minimumCapacity) {/ / overflow-conscious code if (minimumCapacity-value.length > 0) {value = Arrays.copyOf (value, newCapacity (minimumCapacity);}}
3) copy the concatenated string str to the target array value.
Str.getChars (0, len, value, count)
03 、 StringBuffer
First there is StringBuffer and then there is StringBuilder, both are like twins, there should be both, but the eldest brother StringBuffer is thread-safe because he takes two more breaths of fresh air.
Public synchronized StringBuffer append (String str) {toStringCache = null; super.append (str); return this;}
The append method of the StringBuffer class has one more keyword synchronized than StringBuilder, but toStringCache = null can be ignored for the time being.
Synchronized is a very familiar keyword in Java, which is a kind of synchronization lock. The method it modifies is called the synchronization method and is thread-safe.
04. Concat method of String class
In terms of posture alone, the concat method of the String class is like the append of the StringBuilder class.
String chenmo = "Silence"; String wanger = "Wang er"; System.out.println (chenmo.concat (wanger))
When the article was written here, I suddenly came up with a wonderful idea. If there are two lines of code:
Chenmo + = wangerchenmo = chenmo.concat (wanger)
How big is the difference between them?
As we have learned before, chenmo + = wanger is actually equivalent to (new StringBuilder (String.valueOf (chenmo) .append (wanger) .toString ().
To explore the difference between the "+" operator and concat, you actually look at the difference between the append method and the concat method.
The source code for the append method has been analyzed before. Let's take a look at the source of the concat method.
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);}
1) if the length of the concatenated string is 0, the string before concatenation is returned.
If (otherLen = = 0) {return this;}
2) copy the character array value of the original string to the variable buf array.
Char buf [] = Arrays.copyOf (value, len + otherLen)
3) copy the concatenated string str into the character array buf and return the new string object.
Str.getChars (buf, len); return new String (buf, true)
Through the source code analysis, we can roughly draw the following conclusions:
1) if the concatenated string is null,concat, NullPointerException is thrown, and the "+" operator is treated as a "null" string.
2) concat is a little more efficient if the concatenated string is an empty string (""). After all, you don't need a new StringBuilder object.
3) if you concatenate a large number of strings, concat will be less efficient, because the more string objects you create, the more overhead you will spend.
Attention!
Ask weakly, are there any students who are using JSP? The "+" operator is not allowed to concatenate strings in EL expressions, so you can only use concat.
${chenmo.concat ('-') .concat (wanger)}
05. Join method of String class
JDK 1.8 provides a new string concatenation posture: the String class adds a static method join.
String chenmo = "Silence"; String wanger = "Wang er"; String cmower = String.join ("", chenmo, wanger); System.out.println (cmower)
The first parameter is a string concatenator, such as:
String message = String.join ("-", "Wang er", "too special", "interesting")
The output is: Wang er-too special-interesting
Let's look at the source code of the join method:
Public static String join (CharSequence delimiter, CharSequence... Elements) {Objects.requireNonNull (delimiter); Objects.requireNonNull (elements); / / Number of elements not likely worth Arrays.stream overhead. StringJoiner joiner = new StringJoiner (delimiter); for (CharSequence cs: elements) {joiner.add (cs);} return joiner.toString ();}
Found a new class StringJoiner, the class name looks very 6, and it is easy to read. StringJoiner is a class in the java.util package that is used to construct a sequence of characters reconnected by delimiters. Limited to space, this article will no longer do too much introduction, interested students can go to understand.
06 、 StringUtils.join
In practical projects, we often use this class-org.apache.commons.lang3.StringUtils when dealing with strings. The join method of this class is a new posture for string concatenation.
String chenmo = "Silence"; String wanger = "Wang er"; StringUtils.join (chenmo, wanger)
This method is better at concatenating strings in arrays and doesn't have to worry about NullPointerException.
StringUtils.join (null) = nullStringUtils.join ([]) = "" StringUtils.join ([null]) = "" StringUtils.join (["a", "b", "c"]) = "abc" StringUtils.join ([null, "", "a"]) = "a"
By looking at the source code, we can see that StringBuilder is still used internally.
Public static String join (final Object [] array, String separator, final int startIndex, final int endIndex) {if (array = = null) {return null;} if (separator = = null) {separator = EMPTY;} final StringBuilder buf = new StringBuilder (noOfItems * 16); for (int I = startIndex; I)
< endIndex; i++) { if (i >StartIndex) {buf.append (separator);} if (array [I]! = null) {buf.append (Array [I]);}} return buf.toString ();}
When you read this, you will have such a feeling: I rely on (the sound has to be lengthened). Unexpectedly, there are six postures for string stitching. I must try them one by one when I get home at night.
07. Give an answer to the side dish
I'm sure when Xiao Cai reads this article, he will understand why Alibaba doesn't recommend using the "+" operator for string concatenation in the for loop.
Let's look at two pieces of code.
In the first paragraph, the "+" operator is used in the for loop.
String result = ""; for (int I = 0; I < 1000000; iTunes +) {result + = "BHC";}
The second paragraph, append is used in the for loop.
StringBuilder sb = new StringBuilder (); for (int I = 0; I < 1000000; iTunes +) {sb.append (BHC);}
How long will each of these two pieces of code take? The result of the test on my iMac is:
1) the execution time of the first piece of code is 6212 milliseconds.
2) the execution time of the second code is 1 millisecond
The gap is so fucking big! Why?
I believe many students already have their own answers: a large number of StringBuilder objects are created in the for loop in the first paragraph, while the second code has only one StringBuilder object from beginning to end.
Thank you for reading! This is the end of this article on "how to achieve string concatenation in Java". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.