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

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

Guava库中Booleans类的lastIndexOf()方法用于查找布尔数组中给定的布尔值的最后索引。这个要搜索的布尔值和要搜索的布尔数组都作为参数传递给这个方法。它返回一个整数,这个整数是指定布尔值的最后一个索引。如果没有找到该值,它将返回-1。

语法:

public static int lastIndexOf(boolean[] array,
                              boolean target)

参数: 该方法接受两个强制性参数。

  • array:这是一个布尔值数组,布尔值将在其中搜索。
  • target:是布尔数组中最后一个索引要搜索的布尔值。

返回值: 该方法返回一个整数,它是指定布尔值的最后一个索引。如果没有找到该值,则返回-1。

下面的程序说明了这种方法。

例子-1。

// Java code to show implementation of
// Guava's Booleans.lastIndexOf() method
  
import com.google.common.primitives.Booleans;
import java.util.Arrays;
  
class GFG {
  
    // Driver's code
    public static void main(String[] args)
    {
        // Creating a boolean array
        boolean[] arr = { true, false, false,
                          true, true };
  
        boolean target = true;
  
        // Using Booleans.lastIndexOf() method
        // to get the index of last appearance
        // of a given element in array
        // and return -1 if element
        // is not found in the array
        int index = Booleans.lastIndexOf(arr, target);
  
        if (index != -1) {
            System.out.println("Target is present at index "
                               + index);
        }
        else {
            System.out.println("Target is not present "
                               + "in the array");
        }
    }
}

输出:

Target is present at index 4

例子-2。

// Java code to show implementation of
// Guava's Booleans.lastIndexOf() method
  
import com.google.common.primitives.Booleans;
import java.util.Arrays;
  
class GFG {
  
    // Driver's code
    public static void main(String[] args)
    {
        // Creating a boolean array
        boolean[] arr = { true, true, true,
                          true, true };
  
        boolean target = false;
  
        // Using Booleans.lastIndexOf() method to get the
        // index of last appearance of a given element
        // in array and return -1 if element is
        // not found in the array
        int index = Booleans.lastIndexOf(arr, target);
  
        if (index != -1) {
            System.out.println("Target is present at index "
                               + index);
        }
        else {
            System.out.println("Target is not present "
                               + "in the array");
        }
    }
}

输出:

Target is not present in the array

参考资料:

https://google.github.io/guava/releases/20.0/api/docs/com/google/common/primitives/Booleans.html#lastIndexOf-boolean:A-boolean-

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程