Home >Java >javaTutorial >How to find the position of an element in a Java array?
1. BinarySearch concept
binarySearch() method provides a variety of overloaded forms to meet the search needs of various types of arrays .
2. Search attention
Before using the Arrays.binarySearch method, you need to sort the array to locate the value insertion position, because binarySearch uses the binary search method
3. Find the instance
Use the binarySearch() method to find the position of the element in the array.
import java.util.*; public class Test{ public static void main(String args[]) { int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 }; Arrays.sort(array); for (int x:array) { System.out.println(x); } int index = Arrays.binarySearch(array, 2); System.out.println("元素 2 在第 " + index + " 个位置"); } } /* 输出结果: -9 -7 -3 -2 0 2 4 5 6 8 元素 2 在第 5 个位置 */
The above is the detailed content of How to find the position of an element in a Java array?. For more information, please follow other related articles on the PHP Chinese website!