在Java中,String
的join
、concat
和+
操作符是用于拼接字符串的三种不同方法,各自有不同的使用场景和性能特点:
+
操作符:- 最直观和常用的字符串拼接方式。
- 在内部,Java编译器会将
+
操作符转换成使用StringBuilder
的append
方法来拼接字符串。 - 对于少量的字符串拼接操作和简单的使用场景,
+
是很方便的。 - 在循环或频繁操作中使用
+
可能会导致性能下降,因为每次拼接都会创建新的StringBuilder
对象。
concat
方法:String
类的一个方法,专门用于拼接两个字符串。- 使用方式为:
str1.concat(str2)
。 - 相对于
+
,concat
在语义上更明确,表示字符串的拼接操作。 - 但和
+
一样,如果在循环中频繁使用concat
,也可能导致性能问题,因为每次调用都会创建一个新的字符串对象。
join
方法:- 在Java 8中引入的一个静态方法,用于拼接由某个分隔符分隔的多个字符串。
- 使用方式为:
String.join(delimiter, elements...)
。 - 这是一种更高级的拼接方式,特别适合于拼接字符串数组或集合,可以一次性拼接多个元素,并且可以指定元素之间的分隔符。
- 内部实现也是使用
StringBuilder
,但它是一种更有效率的方式,特别是在拼接大量字符串时。
总结:
- 对于简单的拼接,
+
操作符通常是最方便的。 - 如果你需要拼接两个字符串并且关注性能,
concat
是一个好选择。 - 如果你要拼接多个字符串或数组、集合,并且需要分隔符,
join
是最佳选择。 - 在处理大量数据或性能敏感的场景中,应避免在循环中使用
+
和concat
。相反,可以考虑使用StringBuilder
的append
方法或String.join
来提高性能。
package commonTest1221;
/**
* Demo class
*
* @author bootsCoder
* @date created on 2023/12/21
*/
public class Test {
public static void main(String[] args) {
String s1 = "a"+"b";
/**
* Concatenates the specified string to the end of this string.
* <p>
* If the length of the argument string is {@code 0}, then this
* {@code String} object is returned. Otherwise, a
* {@code String} object is returned that represents a character
* sequence that is the concatenation of the character sequence
* represented by this {@code String} object and the character
* sequence represented by the argument string.<p>
* Examples:
* <blockquote><pre>
* "cares".concat("s") returns "caress"
* "to".concat("get").concat("her") returns "together"
* </pre></blockquote>
*
* @param str the {@code String} that is concatenated to the end
* of this {@code String}.
* @return a string that represents the concatenation of this object's
* characters followed by the string argument's characters.
*/
String s2 = s1.concat("c");
/**
* Returns a new String composed of copies of the
* {@code CharSequence elements} joined together with a copy of
* the specified {@code delimiter}.
*
* <blockquote>For example,
* <pre>{@code
* String message = String.join("-", "Java", "is", "cool");
* // message returned is: "Java-is-cool"
* }</pre></blockquote>
*
* Note that if an element is null, then {@code "null"} is added.
*
* @param delimiter the delimiter that separates each element
* @param elements the elements to join together.
*
* @return a new {@code String} that is composed of the {@code elements}
* separated by the {@code delimiter}
*
* @throws NullPointerException If {@code delimiter} or {@code elements}
* is {@code null}
*
* @see java.util.StringJoiner
* @since 1.8
*/
String s3 = String.join(s2,"d");
System.out.println(s1+s2+s3);
}
}