Guava Chars.toArray() 方法与实例
Guava库中Chars类的toArray()方法用于将作为参数传递给该方法的char值转换成Char数组。这些char值被作为一个集合传递给这个方法。该方法返回一个Char数组.
语法:
public static char[] toArray(Collection
collection)
参数: 这个方法接受一个强制参数collection,它是要转换为char数组的char值的集合。
返回值: 该方法返回一个char数组,包含与collection相同的值,顺序相同。
异常情况: 如果传递的集合或其任何元素为空,该方法会抛出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<Character> 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<Character> 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.util.Collection)
