Java can efficiently judge whether there is a detailed explanation of an element in the array

1、 Method to check whether the array contains a value

Use list

Use set

Use circular judgment

Use arrays binarySearch()

Arrays. Binarysearch() method can only be used for ordered arrays!!! If the array is unordered, the result will be strange.

The usage of finding whether an ordered array contains a value is as follows:

Time complexity

The following code can roughly get the time cost of various methods. The basic idea is to find a value from the array. The size of the array is 5, 1K and 10K respectively. The results obtained by this method may not be accurate, but it is the simplest and clear way.

Operation results:

Use an array with a length of 1K

result:

Use an array with a length of 10K

result:

Summary

Obviously, using a simple loop method is more efficient than using any collection. Many developers use the first method for convenience, but its efficiency is also relatively low. Because to push the array into the collection type, you must first traverse the array elements, and then use the collection class to do other operations.

If you use arrays Array must be sorted for binarysearch() method. This method is not available because the above array is not sorted.

In fact, if you need to efficiently check whether an array contains specific values with the help of an array or collection class, a sorted list or tree can achieve a time complexity of O (log (n)), and HashSet can achieve o (1).

Using arrayutils

In addition to the above, the Apache commons class library also provides an arrayutils class, which can use its contains method to judge the relationship between arrays and values.

We also use the arrays of the above lengths to test. The result is that the efficiency of this method is between using set and using loop judgment (sometimes the result is even better than using loop).

In fact, if you look at arrayutils It can be found from the source code of contains that it is actually a circular judgment method to judge whether an element is included in the array.

Some codes are as follows:

Therefore, in contrast, I prefer to use the arrayutils tool class to perform some composite ancestor related operations. After all, he can let me write a lot less code (because it is inevitable that there are bugs when I write code. After all, the open source tool class libraries provided by Apache have been tested by countless developers), and the efficiency is not too low.

summary

Well, the above is the whole content of this article. I hope the content of this article can help you learn or use Java. If you have any questions, you can leave a message.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>