1. 使用for循环遍历数组:
public class ArrayIndex {
public static int getIndex(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
return i;
}
}
return -1; // 如果找不到目标元素,返回-1
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int target = 3;
int index = getIndex(arr, target);
System.out.println("目标元素的下标为: " + index);
}
}
2. 使用Java 8的IntStream:
import java.util.stream.IntStream;
public class ArrayIndex {
public static int getIndex(int[] arr, int target) {
return IntStream.of(arr).boxed().collect(Collectors.toList()).indexOf(target);
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int target = 3;
int index = getIndex(arr, target);
System.out.println("目标元素的下标为: " + index);
}
}
3. 使用方括号运算符和元素索引直接获取元素下标:
int[] numbers = {10, 20, 30, 40, 50};
int index = numbers; // 获取索引为2的元素(值为30)
System.out.println("元素30的下标为: " + index);
4. 使用二分查找算法(折半查找)在有序数组中查找元素的下标:
public class ArrayIndex {
public static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1; // 如果找不到目标元素,返回-1
}
public static void main(String[] args) {
int[] nums = {15, 13, 27, 11, 55, 45, 23, 28};
int num = 45;
int index = binarySearch(nums, num);
System.out.println(num + "在数组中的位置上为: " + index);
}
}
以上是几种查询数组下标的方法。请根据你的具体需求选择合适的方法