Java StringJoiner setEmptyValue()方法

Java StringJoiner setEmptyValue()方法

StringJoiner的setEmptyValue(CharSequence emptyValue)设置了在确定这个StringJoiner的字符串表示时使用的字符序列,并且还没有添加任何元素,也就是说,当它是空的。空值参数的副本就是为了这个目的。注意,一旦调用了add方法,StringJoiner就不再被认为是空的,即使添加的元素与空的String对应。

语法

public StringJoiner setEmptyValue(CharSequence emptyValue)

参数。该方法接受一个强制性参数emptyValue,它是作为空的StringJoiner的值返回的字符。

返回。该方法返回这个StringJoiner本身,所以调用可以是连锁的。

异常情况。当参数emptyValue为空时,该方法抛出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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程