Guava – Shorts.toArray()方法及实例

Guava – Shorts.toArray()方法及实例

Guava库中Shorts类的toArray()方法是用来将作为参数传递给该方法的短值转换成短数组。这些短值被作为一个集合传递给这个方法。该方法返回一个短数组。

语法:

public static short[] toArray(Collectioncollection)

参数: 这个方法接受一个强制性的参数集合,它是要转换为短数组的短值集合。

返回值: 该方法返回一个短数组,包含与集合相同的值,顺序相同。

异常情况:如果传递的集合或其任何元素为空,该方法会抛出NullPointerException。

以下程序说明了toArray()方法的使用。

例1:

// Java code to show implementation of
// Guava's Shorts.toArray() method
  
import com.google.common.primitives.Shorts;
import java.util.Arrays;
import java.util.List;
  
class GFG {
  
    // Driver's code
    public static void main(String[] args)
    {
  
        // Creating a List of Shorts
        List<Short> myList
            = Arrays.asList((short)1, (short)2,
                            (short)3, (short)4, (short)5);
  
        // Using Shorts.toArray() method to convert
        // a List or Set of Short to an array of Short
        short[] arr = Shorts.toArray(myList);
  
        // Displaying an array containing each
        // value of collection,
        // converted to a short value
        System.out.println(Arrays.toString(arr));
    }
}

输出:

[1, 2, 3, 4, 5]

例2:

// Java code to show implementation of
// Guava's Shorts.toArray() method
  
import com.google.common.primitives.Shorts;
import java.util.Arrays;
import java.util.List;
  
class GFG {
  
    // Driver's code
    public static void main(String[] args)
    {
  
        try {
            // Creating a List of Shorts
            List<Short> myList
                = Arrays.asList((short)2,
                                (short)4, null);
  
            // Using Shorts.toArray() method
            // to convert a List or Set of Short
            // to an array of Short.
            // This should raise "NullPointerException"
            // as the collection contains "null"
            // as an element
            short[] arr = Shorts.toArray(myList);
  
            // Displaying an array containing each
            // value of collection,
            // converted to a short value
            System.out.println(Arrays
                                   .toString(arr));
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}

输出:

java.lang.NullPointerException

参考资料:

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程