Check Element in Java Array

In Java, you can either use the binarySearch() method in the Arrays class or write your own loop to determine if an element is in an array.

Before using the binarySearch() method, it is necessary to sort the array first. After sorting, call the method which will then return the index of the element you are looking for in the array. If the returned index is greater than or equal to 0, it means that the element exists in the array. Otherwise, it means that the element is not in the array.

The example code is as follows:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int target = 3;

        // 先对数组进行排序
        Arrays.sort(arr);

        // 使用binarySearch()方法判断元素是否存在
        int index = Arrays.binarySearch(arr, target);
        if (index >= 0){
            System.out.println(target + " 在数组中存在");
        } else {
            System.out.println(target + " 不在数组中存在");
        }
    }
}

Additionally, you can also write a loop to check if an element is in the array. The code is as follows:

public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int target = 3;
        boolean exists = false;

        // 使用循环判断元素是否存在
        for (int i : arr) {
            if (i == target) {
                exists = true;
                break;
            }
        }

        if (exists) {
            System.out.println(target + " 在数组中存在");
        } else {
            System.out.println(target + " 不在数组中存在");
        }
    }
}
bannerAds