How to efficiently determine whether a particular value is contained in an array in Java

Source: Internet
Author: User

Four different ways to check if an array contains a value

Use list:
public static Boolean uselist (string[] arr, String targetvalue) {        return arrays.aslist (arr). Contains (Targetvalue);    }

Use Set:
public static Boolean Useset (string[] arr, String targetvalue) {        set<string> Set = new Hashset<string> (Ar Rays.aslist (arr));        Return Set.contains (Targetvalue);    }

Use a simple looping statement:
public static Boolean Useloop (string[] arr, string targetvalue) {for        (string s:arr) {            if (s.equals (Targetvalue) )                return true;        }        return false;    }

Use the Arrays.binarysearch () method:

The following code is wrong and is listed below for completeness (four ways of judging), BinarySearch () binary lookup can only be used for ordered arrays.

Run the following program, you may get abnormal results;

public static Boolean Usearraysbinarysearch (string[] arr, String targetvalue) {        int a = Arrays.binarysearch (arr, Targ Etvalue);        if (a > 0)            return true;        else            return false;    }

The time cost of the four implementation modes

the array size is 5:

public static void Main (string[] args) {
string[] arr = new string[] {"CD", "BC", "EF", "DE", "AB"};
Use list
Long startTime = System.nanotime ();
for (int i = 0; i < 100000; i++) {
Uselist (arr, "A");
}
Long endTime = System.nanotime ();
Long Duration = Endtime-starttime;
System.out.println ("uselist:" + duration/1000000);
Use Set
StartTime = System.nanotime ();
for (int i = 0; i < 100000; i++) {
Useset (arr, "A");
}
EndTime = System.nanotime ();
Duration = Endtime-starttime;
System.out.println ("Useset:" + duration/1000000);
Use loop
StartTime = System.nanotime ();
for (int i = 0; i < 100000; i++) {
Useloop (arr, "A");
}
EndTime = System.nanotime ();
Duration = Endtime-starttime;
System.out.println ("Useloop:" + duration/1000000);
Use Arrays.binarysearch ()
StartTime = System.nanotime ();
for (int i = 0; i < 100000; i++) {
Usearraysbinarysearch (arr, "A");
}
EndTime = System.nanotime ();
Duration = Endtime-starttime;
System.out.println ("usearraybinary:" + duration/1000000);
}

Operation Result:

Uselist:13
useset:72
Useloop:5
Usearraysbinarysearch:9the array size is:
string[] arr = new string[1000];        Random s = new Random ();        for (int i = 0; i < i++) {            Arr[i] = string.valueof (S.nextint ());        } Operation Result:
uselist:112 useset:2055 useloop:99 usearraybinary:12 Conclusion:

As you can see from the test results, using a simple loop statement is more efficient than using any set, and a large percentage of developers choose to use the first method (List), but this approach is relatively inefficient. Before using the API provided by the collection, it is necessary to put an array into the collection, which takes a certain amount of time, especially for the set set; (Note: The performance of the ArrayList collection is similar to that of a normal loop statement, because for ArrayList, when converted to a set, Just changing the internal array index, traversing the judgment, similar to the normal loop statement);

If you want to use the Arrays.binarysearch () method, as long as the array is ordered, in this test demo, it is clear that the array is unordered and therefore should not be used;

In fact, if you do need to efficiently check whether an array or collection contains a value, an ordered list or ordered tree can reduce the complexity of time to O (log (n)), or use a hash set, with a time complexity of O (1);

Link: http://www.programcreek.com/2014/04/check-if-array-contains-a-value-java/

Connected to the same code farm: http://www.cnblogs.com/chenpi/category/783125.html

Quote Original: http://blog.csdn.net/sinat_33536912/article/details/52093989

Blog is to remember that they are easy to forget things, but also a summary of their work, the article can be reproduced, without copyright. Hope to do their own efforts to do better, we work together to improve!

If there is any problem, welcome to discuss together, code if there is a problem, you are welcome to the great God!

How to efficiently determine whether a particular value is contained in an array in Java

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.