In this post under Java Collections, I will show with example how to search an array for a specific element.
Please note there is a precondition that must be satisfied before searching an array. The precondition is that the array should already be sorted.
Java “Arrays” class provides “binarySearch” method which does the searching. This method takes below two arguments
1) The sorted array
2) The element to be searched for
If the element is found the method returns the index where the element is present.
If the element is not found the method returns -(the index where the element has to inserted to maintaing the sort order + 1).
Below is the complete main class for your reference
Main class
1 package core.collection;
2
3 import java.util.Arrays;
4
5 public class SearchingArrayDemo {
6 public static void main(String[] args) {
7 int[] intArray = new int[]{1, 2, 3, 4, 5};
8 int index = Arrays.binarySearch(intArray, 2);
9 System.out.println("index for element 2: " + index);
10 index = Arrays.binarySearch(intArray, 6);
11 System.out.println("index for element 6: " + index);
12 }
13 }
In this way an element is search in an array.
Output
index for element 2: 1
index for element 6: -6