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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值