當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。