Home > Java > javaTutorial > body text

How to find the position of an element in a Java array?

WBOY
Release: 2023-04-22 17:43:08
forward
3429 people have browsed it

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 个位置
 */
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template