在Java中,有很多串联字符串和添加变量值的方法。选择哪一种方法(优缺点和最好使用场景等)?
- MessageFormat.format
- String.format
- "string a" + "string b"
- StringBuilder
- StringBuffer
- String.concat
- 流(Streams)
- String.join()
- Apache Commons’ StringUtils
- Google Guava’s Joiner
- ...
在Java中,有很多串联字符串和添加变量值的方法。选择哪一种方法(优缺点和最好使用场景等)?
MessageFormat.format() - 用于动态创建字符串,其中字符串的某些部分被定位,参数填充这些位置。
MessageFormat.format("我的名字是{0}。我今年{1}岁了", "Vignesh", 24);
String.format() - 类似于 MessageFormat 中的定位编号,它接受参数类型说明符。
String.format("π等于%.2f", 3.14)
String+String - string+string 会生成一个新的字符串,旧的字符串会留在垃圾内存中,并在稍后被 JVM 清除。 它内部被转换为 StringBuilder.append() 和 toString() 方法。
hello+world=helloworld
null+hello=nullhello
String.concat() - 与 string+string 不同,如果调用 concat 方法的对象为 null,则会抛出 NullPointerException。
String a = null, b="hello"; a.concat(b) 抛出 NullPointerException
StringBuffer - 它们是可变的,但由于其内部方法已同步,因此速度较慢。即线程安全的。
StringBuffer sb = new StringBuffer();
sb.append("hello").append("world");
sb.toString();
StringBuilder - 它们是可变的,比 StringBuffer 更快,但不是线程安全的。
StringBuilder sb = new StringBuilder();
sb.append("hello").append("world");
sb.toString();
String.join - 如果要连接的字符串是以数组形式存在的,最好使用String.join,而不是通过循环遍历数组并使用StringBuilder进行追加,因为String.join已经在内部执行了此操作。如果传递的数组为null
,它会抛出NullPointerException
异常。
String[] a = {"hello", "world"};
String.join("", a)
StringUtils.join - 如果要连接的字符串是以数组形式存在的,也可以使用它。它在内部使用StringBuilder。但仅仅为了字符串连接并不需要包含一个jar。它根据数组中元素的数量预先计算了StringBuilder对象的capacity
。如果传递的数组为null
,它不会抛出异常,而只是返回null
字符串。
String[] a = {"hello", "world"};
StringUtils.join(a, "")