I have a String[]
with values like so:
public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
Given String s
, is there a good way of testing whether VALUES
contains s
?
I have a String[]
with values like so:
public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
Given String s
, is there a good way of testing whether VALUES
contains s
?
For arrays of limited length use the following (as given by camickr). This is slow for repeated checks, especially for longer arrays (linear search).
For fast performance if you repeatedly check against a larger set of elements
An array is the wrong structure. Use a
TreeSet
and add each element to it. It sorts elements and has a fastexist()
method (binary search).If the elements implement
Comparable
& you want theTreeSet
sorted accordingly:ElementClass.compareTo()
method must be compatable withElementClass.equals()
: see Triads not showing up to fight? (Java Set missing an item)Otherwise, use your own
Comparator
:The payoff: check existence of some element:
For what its worth I ran a test comparing the 3 suggestions for speed. I generated random integers, converted them to a String and added them to an array. I then searched for the highest possible number/string, which would be a worst case scenario for the asList().contains().
When using a 10K array size the results where:
When using a 100K array the results where:
So if the array is created in sorted order the binary search is the fastest, otherwise the asList().contains would be the way to go. If you have many searches, then it may be worthwhile to sort the array so you can use the binary search. It all depends on your application.
I would think those are the results most people would expect. Here is the test code:
You can use the Arrays class to perform a binary search for the value. If your array is not sorted, you will have to use the sort functions in the same class to sort the array, then search through it.
Developers often do:
The above code works, but there is no need to convert a list to set first. Converting a list to a set requires extra time. It can as simple as:
or
The first one is more readable than the second one.
If you have the google collections library, Tom's answer can be simplified a lot by using ImmutableSet (http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/ImmutableSet.html)
This really removes a lot of clutter from the initialization proposed
Try this: