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