Guava – Shorts.lastIndexOf()方法及实例
Guava库中Shorts类的lastIndexOf()方法用于查找短数组中给定短值的最后索引。这个要搜索的短值和要搜索的短数组都作为一个参数传递给这个方法。它返回一个整数,这个整数是指定短值的最后索引。如果没有找到该值,它将返回-1。
语法:
public static int lastIndexOf(short[] array, short target)
参数:该方法接受两个强制性参数。
array:是短值的数组,短值将在其中被搜索到。target:是短数组中最后一个索引要搜索的短值。返回值: 该方法返回一个整数,该整数是指定短值的最后一个索引。如果没有找到该值,则返回-1。
下面的程序说明了这种方法。
例1:
// Java code to show implementation of// Guava's Shorts.lastIndexOf() method import com.google.common.primitives.Shorts;import java.util.Arrays; class GFG { // Driver's code public static void main(String[] args) { // Creating a short array short[] arr = { 1, 2, 3, 4, 3, 5, 3, 4 }; short target = 3; // Using Shorts.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 = Shorts.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 6
例2:
// Java code to show implementation of// Guava's Shorts.lastIndexOf() method import com.google.common.primitives.Shorts;import java.util.Arrays; class GFG { // Driver's code public static void main(String[] args) { // Creating a short array short[] arr = { 3, 5, 7, 11, 13 }; short target = 17; // Using Shorts.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 = Shorts.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/23.0/api/docs/com/google/common/primitives/Shorts.html#lastIndexOf-short:A-short-
