Guava – Longs.toArray()方法与实例

Guava – Longs.toArray() 方法与实例

The toArray() method of Guava库中的Longs类 ,用于将作为参数传递给该方法的长值转换成长数组。这些长值被作为一个集合传递给这个方法。该方法返回一个Long数组。

语法:

public static long[] toArray(Collection<? extends Number> collection)

参数: 这个方法接受一个强制参数collection,它是要转换为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<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

参考:

https://google.github.io/guava/releases/21.0/api/docs/com/google/common/primitives/Longs.html#toArray-java.util.Collection-

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程