How to Check if an Array Contains a Value in Java Efficiently?— reference
How to check if an array (unsorted) contains a certain value? This is a very useful and frequently used operation in Java. It is also a top Voted question on Stack Overflow. As shown in top Voted answers,checking if an array contains a certain value can be done in several different ways,but the time complexity Could be very different. In the following I will show the time each method takes.
1. 4 Different Ways to Check If an Array Contains a Value
1) Using List:
2) Using Set:
3) Using a simple loop:
4) Using Arrays. binarySearech():
2. Time Complexity
The approximate time complexity can be compared by using the following code. It is not precise,just search an array of size 5,1k,10k,but the idea is clear.
Result:
useList: 13 useSet: 72 useLoop: 5 useArraysBinarySearch: 9
Use a larger array (1k):
Result:
useList: 112 useSet: 2055 useLoop: 99 useArrayBinary: 12
Use a larger array (10k):
Result:
useList: 1590 useSet: 23819 useLoop: 1526 useArrayBinary: 12
Clearly,using a simple loop method is more efficient than using any collection. A lot of developers use the first method,but it is inefficient. Pushing the array to another Collection type will require spin through all elements to read them in before doing anything with the collection type.
The array must be sorted,if Arrays. binarySearch() method is used. In this case,the array is not sorted,therefore,it should not be used.
Actually,if you really need to check if a value is contained in some array/collection efficiently,a sorted list or tree can do it in O(log(n)) or hashset can do it in O(1).
reference from: http://www.programcreek.com/2014/04/check-if-array-contains-a-value-java/