Using custom method
Following is the Java code to check if your array contains any specific element.
public class ArrayContains {
public static void main(String args[]){
int[] myIntArray = {43,32,53,23,12,34,3,12,43,32};
int number = 326;
if(contains(myIntArray,number)){
System.out.println("Number "+number+" is present in array.");
}else{
System.out.println("Number "+number+" not found in array.");
}
}
public static boolean contains(int[] intArray, int number){
for(int i = 0; i < intArray.length; i++){
if(intArray[i] == number){
return true;
}
}
return false;
}
}
Method
contains
returns true if the element is found and returns false if the element is not found. The above code does not use library method to find the element.
Using java.util.Arrays package
There is another fast approach to solve this using
binarySearch
method that is available in
java.util.Arrays package
import java.util.Arrays;
public class ArrayContains {
public static void main(String args[]){
int[] myIntArray = {43,32,53,23,12,34,3,12,43,32};
int number = 362;
Arrays.sort(myIntArray);
if(Arrays.binarySearch(myIntArray, number) >= 0){
System.out.println("Number "+number+" is present in array.");
}else{
System.out.println("Number "+number+" not found in array.");
}
}
}
We have used the predefined library method
binarySearch
to check if the element exists in the Array. Notice that for binarySearch to work, the array needs to sorted and therefore we have called
sort
method before performing the search.
binarySearch
returns the index of element in the Array if the element is found. If not it will return the (-(
insertion point) – 1) index of element we are searching.
Using org.apache.commons.lang3.ArrayUtils package
import org.apache.commons.lang3.ArrayUtils;
public class ArrayContains {
public static void main(String args[]){
int[] myIntArray = {43,32,53,23,12,34,3,12,43,32};
int number = 362;
if(ArrayUtils.contains(myIntArray,number)){
System.out.println("Number "+number+" is present in array.");
}else{
System.out.println("Number "+number+" not found in array.");
}
}
}