java string set_Java StringJoiner setEmptyValue()用法及代码示例
StringJoiner的setEmptyValue(CharSequence emptyValue)设置确定此StringJoiner的字符串表示形式且尚未添加任何元素(即当它为空时)时要使用的字符序列。为此,复制了emptyValue参数。请注意,一旦调用了add方法,即使添加的元素对应于空字符串,StringJoiner也不再被认为是空的。
用法:
public StringJoiner setEmptyValue(CharSequence emptyValue)
参数:此方法接受强制性参数emptyValue,该参数将作为空StringJoiner的值返回的字符
返回值:此方法返回此StringJoiner本身,因此调用可以链接在一起
异常:当emptyValue参数为null时,此方法引发NullPointerException
以下示例说明了setEmptyValue()方法:
示例1:
// Java program to demonstrate
// setEmptyValue() method of StringJoiner
import java.util.StringJoiner;
public class GFG {
public static void main(String[] args)
{
// Create a StringJoiner
StringJoiner str = new StringJoiner(" ");
// Print the empty StringJoiner
System.out.println("Initial StringJoiner: "
+ str);
// Add an emptyValue
// using setEmptyValue() method
str.setEmptyValue("StrigJoiner is empty");
// Print the StringJoiner
System.out.println("After setEmptyValue(): "
+ str);
// Add elements to StringJoiner
str.add("Geeks");
str.add("forGeeks");
// Print the StringJoiner
System.out.println("Final StringJoiner: "
+ str);
}
}
输出:
Initial StringJoiner:
After setEmptyValue(): StrigJoiner is empty
Final StringJoiner: Geeks forGeeks
示例2:演示NullPointerException
// Java program to demonstrate
// setEmptyValue() method of StringJoiner
import java.util.StringJoiner;
public class GFG {
public static void main(String[] args)
{
// Create a StringJoiner
StringJoiner str = new StringJoiner(" ");
// Print the empty StringJoiner
System.out.println("Initial StringJoiner: "
+ str);
try {
// Add a null emptyValue
// using setEmptyValue() method
str.setEmptyValue(null);
}
catch (Exception e) {
System.out.println("Exception when adding null"
+ " in setEmptyValue(): " + e);
}
}
}
输出:
Initial StringJoiner:
Exception when adding null in setEmptyValue():
java.lang.NullPointerException:
The empty value must not be null
总结
以上是生活随笔为你收集整理的java string set_Java StringJoiner setEmptyValue()用法及代码示例的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: pcam00是什么手机型号
- 下一篇: java 泛型和集合_Java集合和泛型