Whether an array contains a value.
1. Check whether the array contains four different methods of specific values
1) Use List:
Public static boolean useList (String [] arr, String targetValue ){
Return Arrays. asList (arr). contains (targetValue );
}
2) use Set:
Public static boolean useSet (String [] arr, String targetValue ){
Set <String> set = new HashSet <String> (Arrays. asList (arr ));
Return set. contains (targetValue );
}
3) use a simple loop:
Public static boolean useLoop (String [] arr, String targetValue ){
For (String s: arr ){
If (s. equals (targetValue ))
Return true;
}
Return false;
}
4) use Arrays. binarySearch ():
Note: The following code is incorrect. It is written for easy understanding. BinarySearch () can only be used in sorted arrays. Therefore, you will find the following results very strange.
Public static boolean useArraysBinarySearch (String [] arr, String targetValue ){
Int a = Arrays. binarySearch (arr, targetValue );
If (a> 0)
Return true;
Else
Return false;
}