"Simple Java" how to efficiently determine if a particular value is contained in an array

Source: Internet
Author: User

How can I tell if an unordered array contains a specific value? This is a very practical operation in Java, and is also a hot issue in the stack Overflow FAQ site;

To complete this judgment, can be achieved through a number of different ways, each of the implementation of the corresponding time complex reading will be very different;

Next I'll show the time overhead for different implementations.

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) {        Setnew hashset<string>(arrays.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))                returntrue;         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, Targetvalue);         if (A > 0)             return true ;         Else            return false ;    }
The time cost of the four implementation modes

The following code calculates the approximate time consumption of the above four implementations, the basic strategy is to use different size arrays (5,1k,10k) to do the test, may not be very accurate, but this method is very simple;

the array size is 5:
 Public Static voidMain (string[] args) {string[] arr=NewString[] {"CD", "BC", "EF", "DE", "AB" }; //Use list        LongStartTime =System.nanotime ();  for(inti = 0; I < 100000; i++) {uselist (arr),A); }        LongEndTime =System.nanotime (); LongDuration = EndTime-StartTime; System.out.println ("Uselist:" + duration/1000000); //Use setStartTime =System.nanotime ();  for(inti = 0; I < 100000; i++) {Useset (arr),A); } endTime=System.nanotime (); Duration= EndTime-StartTime; System.out.println ("Useset:" + duration/1000000); //Use loopStartTime =System.nanotime ();  for(inti = 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(inti = 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:
        New string[1000];         New Random ();          for (int i = 0; i < i++) {            = string.valueof (S.nextint ());        }

Operation Result:

uselist:112
useset:2055
useloop:99
Usearraybinary:12the array size is 10000:
        New string[10000];         New Random ();          for (int i = 0; i < 10000; i++) {            = string.valueof (S.nextint ());        }

Operation Result:

uselist:1590
useset:23819
useloop:1526
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/

"Simple Java" how to efficiently determine if a particular value is contained in an array

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.