当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Guava Chars.toArray()用法及代码示例


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

用法:

public static char[] toArray(Collection<Character> collection)



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

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

异常:如果传递的集合或其任何元素为null,则此方法将引发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)



相关用法


注:本文由纯净天空筛选整理自Sahil_Bansall大神的英文原创作品 Java Guava | Chars.toArray() method with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。