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
相關用法
- Java Guava Ints contains()用法及代碼示例
- Java Guava Ints max()用法及代碼示例
- Java Guava Ints min()用法及代碼示例
- Java Guava Ints asList()用法及代碼示例
- Java Guava Ints lastIndexOf()用法及代碼示例
- Java Guava Ints concat()用法及代碼示例
- Java Guava Ints indexOf()用法及代碼示例
- Java Guava Ints join()用法及代碼示例
- Java Guava Ints.compare()用法及代碼示例
- Java Guava Ints.hashCode()用法及代碼示例
- Java Ints.indexOf(int[] array, int[] target)用法及代碼示例
- Java Guava Bytes.toArray()用法及代碼示例
- Java Guava Longs.toArray()用法及代碼示例
- Java Guava Chars.toArray()用法及代碼示例
注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 Ints toArray() function | Guava | Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。