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, this can be done in several different ways, but the time complexity could be very different. In the following I will show the time cost of each method.
<span id="ezoic-pub-ad-placeholder-" null"="" class="ezoic-adpicker-ad" style="margin: 0px; padding: 0px;">
1. Four Different Ways to Check If an Array Contains a Value
1) Using
List
:
2) Using Set
:
3) Using a simple loop:
4) Using Arrays.binarySearch()
:
binarySearch()
can ONLY be used on sorted arrays. If the array is sorted, you can use the following code to search the target element:
2. Time Complexity
The approximate time cost can be measured by using the following code. The basic idea is to search an array of size 5, 1k, 10k. The approach may not be precise, but the idea is clear and simple.
Result:
useList: 13 useSet: 72 useLoop: 5
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 requires 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 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)
.