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


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


Guava的Ints.toArray()返回包含每个collection值的数组,并以Number.intValue()的方式转换为int值

用法:

public static int[] 
    toArray(Collection<? extends Number> collection)

参数:此方法将集合作为参数,它是Number实例的集合。


返回值:此方法返回一个数组,该数组包含与collection相同的值,并以相同顺序转换为基元。

异常:如果collection或其任何元素为null,则此方法将引发NullPointerException。

以下示例说明了Ints.toArray()方法:

范例1:

// Java code to show implementation of 
// Guava's Ints.toArray() method 
  
import com.google.common.primitives.Ints; 
import java.util.Arrays; 
import java.util.List; 
  
class GFG { 
  
    // Driver's code 
    public static void main(String[] args) 
    { 
  
        // Creating a List of Integers 
        List<Integer> 
            myList = Arrays.asList(1, 2, 3, 4, 5); 
  
        // Using Ints.toArray() method to convert 
        // a List or Set of Integer to an array 
        // of Int 
        int[] arr = Ints.toArray(myList); 
  
        // Displaying an array containing each 
        // value of collection, 
        // converted to a int value 
        System.out.println("Array from given List:"
                           + Arrays.toString(arr)); 
    } 
}
输出:
Array from given List:[1, 2, 3, 4, 5]

范例2:演示NullPointerException

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

参考: https://google.github.io/guava/releases/22.0/api/docs/com/google/common/primitives/Ints.html#toArray-java.util.Collection-



相关用法


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