Guava库中Longs类的toArray()方法用于将作为参数传递给此方法的long值转换为Long Array。这些long值作为Collection传递给此方法。此方法返回一个Long数组。
用法:
public static long[] toArray(Collection<? extends Number> collection)
参数:此方法接受强制性参数集合,该参数集合是要转换为Long数组的long值的集合。
返回值:此方法以相同的顺序返回包含与集合相同的值的长数组。
异常:如果传递的集合或其任何元素为null,则此方法将引发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<Long> 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<Long> 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
相关用法
- Java Guava Doubles.min()用法及代码示例
- Java Guava Doubles.contains()用法及代码示例
- Java Guava Floats.contains()用法及代码示例
- Java Guava Bytes.contains()用法及代码示例
- Java Guava Longs.contains()用法及代码示例
- Java Guava Shorts.min()用法及代码示例
- Java Guava Longs.min()用法及代码示例
- Java Guava Chars.min()用法及代码示例
- Java Guava Floats.min()用法及代码示例
- Java Guava Longs.max()用法及代码示例
- Java Guava Doubles.max()用法及代码示例
- Java Guava Chars.max()用法及代码示例
- Java Guava Floats.max()用法及代码示例
- Java Guava Booleans.contains()用法及代码示例
- Java Guava Shorts.contains()用法及代码示例
注:本文由纯净天空筛选整理自Sahil_Bansall大神的英文原创作品 Java Guava | Longs.toArray() method with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。