📌  相关文章
📜  Java番石榴 |带有示例的 Chars.toArray() 方法

📅  最后修改于: 2022-05-13 01:55:48.525000             🧑  作者: Mango

Java番石榴 |带有示例的 Chars.toArray() 方法

Guava 库中Chars 类toArray()方法用于将作为参数传递给该方法的 char 值转换为 Char 数组。这些 char 值作为 Collection 传递给此方法。此方法返回一个 Char 数组。

句法:

参数:此方法接受一个强制参数集合,该集合是要转换为 Char 数组的 char 值的集合。

返回值:此方法以相同的顺序返回一个包含与集合相同的值的 char 数组。

异常:如果传递的集合或其任何元素为空,则此方法抛出NullPointerException

下面的程序说明了 toArray() 方法的使用:

示例 1:

// Java code to show implementation of
// Guava's Chars.toArray() method
  
import com.google.common.primitives.Chars;
import java.util.Arrays;
import java.util.List;
  
class GFG {
  
    // Driver's code
    public static void main(String[] args)
    {
  
        // Creating a List of Chars
        List myList
            = Arrays.asList('G', 'E', 'E', 'K', 'S');
  
        // Using Chars.toArray() method to convert
        // a List or Set of Char to an array of Char
        char[] arr = Chars.toArray(myList);
  
        // Displaying an array containing each
        // value of collection,
        // converted to a char value
        System.out.println(Arrays.toString(arr));
    }
}
输出:
[G, E, E, K, S]

示例 2:

// Java code to show implementation of
// Guava's Chars.toArray() method
  
import com.google.common.primitives.Chars;
import java.util.Arrays;
import java.util.List;
  
class GFG {
  
    // Driver's code
    public static void main(String[] args)
    {
  
        try {
            // Creating a List of Chars
            List myList
                = Arrays.asList('a', 'b', null);
  
            // Using Chars.toArray() method
            // to convert a List or Set of Char
            // to an array of Char.
            // This should raise "NullPointerException"
            // as the collection contains "null"
            // as an element
            char[] arr = Chars.toArray(myList);
  
            // Displaying an array containing each
            // value of collection,
            // converted to a char value
            System.out.println(Arrays
                                   .toString(arr));
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
输出:
java.lang.NullPointerException

参考 :
https://google.github.io/guava/releases/18.0/api/docs/com/google/common/primitives/Chars.html#toArray(java Java)