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是什么手机型号
- 下一篇: S12卡莎大乱斗出装 天赋怎么选