How to efficiently determine if a Java array contains a value

Source: Internet
Author: User
Tags array length ticket

In Java, how do we tell if an unordered array contains a specific value? This is a frequent and very useful operation in Java. So what is the most efficient way to do that? Of course

, this issue is also a question and answer in stack overflow, which has a very high ticket rate. The first few answers to the ticket rate are the ones that focus on different approaches, but their time complexity is far off.
This article will discuss the main methods in detail and give their respective time losses.
Four methods
List
public static Boolean uselist (string[] arr,string value) {
return arrays.aslist (arr). Contains ( Value);
}
Set
public static Boolean Useset (string[] arr,string value) {
return Sets.contains (value)
}
Loop
public static Boolean Useloop (string[] arr,string value) {
for (String S:arr) {
if (s.equals (value))
Return True
}
return false;
}
BinarySearch
public static Boolean Usebinarysearch (string[] arr,string value) {
int result= Arrays.binarysearch (Arr,value);
if (result>0)
return true;
else
return false;
}
This method is incorrect because the BinarySearch method of arrays must be applied to an ordered array.
Performance Comparison
If the reader is familiar with the centralized data structures that appear in the above Java code snippet, then the time complexity calculation criteria can be used, and the
calculates the approximate results of the performance comparisons of these four methods first. Of course, we do not use this method here, but instead directly use the
test code below to compare the time loss of these four ways. To make our test results more representative, we
do multiple sets of tests for different data volumes. Perhaps, this measurement is not accurate, but the measurement results are clear and can be
trusted. The sample code for the test is as follows:
public static void Main (string[] args) {

string[] arr = new string[] {"www.", "Tiantian", "Bian", "Ma", ". com"};

Long startTime = System.nanotime ();
for (int i = 0; i < 100000; i++) {
Use list
Uselist (arr, "encode every day");
Use Set
Useset (arr, "encode every day");
Use loop
Useloop (arr, "encode every day");
Use BinarySearch
Usebinarysearch (arr, "encode every day");
Long endTime = System.nanotime ();
Long Duration = EndTime = StartTime;
SYSTEM.OUT.PRI}

Array length method running time-consuming array length method runs time-consuming

5 list of list

5 Set 668
5 Loop 5 Loop 47
5 BinarySearch Inarysearch 8
1k List 10k list 1590
1k Set 2055 10k set23819
1k Loop 10k loop1526
1k BinarySearch 10k BinarySearch 12
Summarize
The conclusion of this table is already obvious. The simplest loop method is more efficient than any other method that uses a collection container.
Many of the Open source project codes show that many Java developers prefer to use the first method (list), which in fact does not perform well.
This method transfers the elements of an array to a new collection container, and it is clear that the new collection container is in an unusable state until all the element transitions are complete.

The table also reflects the fact that the performance of the Arrays.binarysearch () method is the best, especially for arrays with large array lengths.
However, this method requires that the array must be ordered, which restricts the use of the method, the array in the example code is not ordered,
Therefore, this method should not be used.

In fact, if you really need to efficiently check whether a particular value is contained in some array or collection container,
You should consider using a sequence table or ordered tree, where the time complexity of finding a particular value is O (log (n)).
Of course, if you use a hash set, the time complexity drops to O (1).

How to efficiently determine if a Java array contains a value

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.