Java Ints toArray() 函数
Guava的 Ints .toArray() 返回一个包含集合中每个值的数组,以Number.intValue()的方式转换为一个int值。
语法
public static int[]
toArray(Collection<? extends Number> collection)
参数。此方法接受集合作为参数,它是一个Number实例的集合。
返回值: 该方法返回一个数组,包含与集合相同的值,以相同的顺序,转换为基数。
异常: 如果集合或其任何元素为空,此方法会抛出 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-