Efficient in Java to determine whether an element exists in an array is detailed _java

Source: Internet
Author: User

A method of checking whether an array contains a value

Using the list

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

Using Set

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

Use circular judgment

public static Boolean Useloop (string[] arr, String targetvalue) {for
  (String s:arr) {
    if s.equals (targetvalue ) return
      true;
  }
  return false;
}

Using Arrays.binarysearch ()

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

The use of finding whether a value is contained in an ordered array is as follows:

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

Complexity of Time

The following code can approximate the time cost of each method. The basic idea is to look for a value from the array, the size of which is 5, 1k, 10k. The results of this approach may not be accurate, but are the simplest and clearest way.

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);}

Run Result:

Uselist:13
useset:72
useloop:5
usearraysbinarysearch:9

Use an array of length 1k

string[] arr = new string[1000];

Random s = new Random ();
for (int i=0; i< 1000 i++) {
  Arr[i] = string.valueof (S.nextint ());
}

Results:

uselist:112
useset:2055
useloop:99
usearraybinary:12

Use an array of length 10k

string[] arr = new string[10000];

Random s = new Random ();
for (int i=0; i< 10000 i++) {
  Arr[i] = string.valueof (S.nextint ());
}

Results:

uselist:1590
useset:23819
useloop:1526
usearraybinary:12

Summary

Obviously, using a simple loop method is more efficient than using any set. Many developers use the first method for convenience, but his efficiency is also relatively low. Because the array is pressed into the collection type, the array element is first traversed, and then the collection class is used to do other things.

If you use a Arrays.binarySearch() method, the array must be sorted. This method is not available because the array above is not sorted.

In fact, if you need an array or collection class to efficiently check whether an array contains a particular value, a sorted list or tree can achieve a time complexity of O (log (n)), and HashSet can reach O (1).

Using Arrayutils

In addition to the above, the Apache Commons Class library also provides a arrayutils class that can use its contains method to determine the relationship between an array and a value.

Import Org.apache.commons.lang3.ArrayUtils;
public static Boolean usearrayutils (string[] arr, String targetvalue) {return
  arrayutils.contains (arr,targetvalue );
}

The result is that the efficiency of the method is between the use of a set and the use of circular judgments (sometimes the results are even better than the use of loops), which are also tested using arrays of several lengths.

uselist:323
useset:3028
useloop:141
usearraybinary:12
usearrayutils:181
-------
uselist:3703
useset:35183
useloop:3218
usearraybinary:14
usearrayutils:3125

In fact, if you look at Arrayutils.contains's source code, he determines whether an element is contained in an array and is actually a way of using circular judgments.

Some of the code is as follows:

  if (array = = null) {
    return-1;
  } else {
    if (StartIndex < 0) {
      startIndex = 0;
    }

    int i;
    if (Objecttofind = = null) {for
      (i = StartIndex i < array.length; ++i) {
        if (array[i] = null) {return
          i;
   }
      }
    else if (Array.getclass (). Getcomponenttype (). Isinstance (Objecttofind)) {for
      (i = StartIndex ; i < Array.Length; ++i) {
        if (objecttofind.equals (Array[i])) {return
          i
        }

    }} return-1;
  }

So, in comparison, I prefer to use the Arrayutils tool class for some of the related operations of the composite ancestor. After all, he can let me write a lot less code (because it is inevitable to write code bugs, after all, Apache has provided the open Source Tool class library has been tested by countless developers), but also not too much efficiency.

Summarize

Well, the above is the entire content of this article, I hope the content of this article for everyone to learn or use Java can have some help, if you have questions you can message exchange.

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.