Guava Ints – toArray() 函数

Guava 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-

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程