Guava – Booleans.toArray()方法及示例

来源:这里教程网 时间:2026-02-17 21:41:14 作者:

Guava – Booleans.toArray()方法及示例

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

语法:

public static boolean[] toArray(Collectioncollection)

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

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

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

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

例1:

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

输出:

[false, true, false, false]

例2:

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

输出:

[true, true, false]

参考资料:

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

相关推荐