Java番石榴 |带有示例的 Longs.toArray() 方法
Guava 库中Longs 类的toArray()方法用于将作为参数传递给该方法的 long 值转换为 Long Array。这些长值作为集合传递给此方法。此方法返回一个 Long 数组。
句法:
public static long[] toArray(Collection extends Number> collection)
参数:此方法接受一个强制参数集合,该集合是要转换为 Long 数组的 long 值的集合。
返回值:此方法返回一个长数组,其中包含与集合相同的值,顺序相同。
异常:如果传递的集合或其任何元素为空,则此方法抛出NullPointerException 。
下面的程序说明了 toArray() 方法的使用:
示例 1:
// Java code to show implementation of
// Guava's Longs.toArray() method
import com.google.common.primitives.Longs;
import java.util.Arrays;
import java.util.List;
class GFG {
// Driver's code
public static void main(String[] args)
{
// Creating a List of Longs
List myList
= Arrays.asList(1L, 2L, 3L, 4L, 5L);
// Using Longs.toArray() method to convert
// a List or Set of Long to an array of Long
long[] arr = Longs.toArray(myList);
// Displaying an array containing each
// value of collection,
// converted to a long value
System.out.println(Arrays.toString(arr));
}
}
输出:
[1, 2, 3, 4, 5]
示例 2:
// Java code to show implementation of
// Guava's Longs.toArray() method
import com.google.common.primitives.Longs;
import java.util.Arrays;
import java.util.List;
class GFG {
// Driver's code
public static void main(String[] args)
{
try {
// Creating a List of Longs
List myList
= Arrays.asList(2L, 4L, null);
// Using Longs.toArray() method
// to convert a List or Set of Long
// to an array of Long.
// This should raise "NullPointerException"
// as the collection contains "null"
// as an element
long[] arr = Longs.toArray(myList);
// Displaying an array containing each
// value of collection,
// converted to a long value
System.out.println(Arrays
.toString(arr));
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
java.lang.NullPointerException
参考: https://google.github.io/guava/releases/21.0/api/docs/com/google/common/primitives/Longs.html#toArray-java.util.Collection-