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
?
I am very late to join this discussion, but since my approach in solving this problem, when I faced it a few years ago, was a bit different than the other answers already posted here, I am posting that solution I used at that time, over here, in case anyone finds it usefull: (The
contains()
method isArrayUtils.in()
in this code.)ObjectUtils.java
ArrayUtils.java
As you can see in the code above, that there are other utility methods
ObjectUtils.equals()
andArrayUtils.indexOf()
, that were used at other places as well.You can use
ArrayUtils.contains
from Apache Commons Langpublic static boolean contains(Object[] array, Object objectToFind)
Note that this method returns
false
if the passed array isnull
.There are also methods available for primitive arrays of all kinds.
Example:
Actually , if you use HashSet as Tom Hawtin proposed you don`t need to worry about sorting and your speed is the same as with Binary Search on a presorted array, probably even faster.
It all depends on how your code is set up, obviously, but from where I stand, the order would be:
On an UNsorted array:
On a sorted array:
So either way, HashSet ftw
With Java 8 you can create a stream and check if any entries in the stream matches
"s"
:Or as a generic method:
Instead of using the quick array initialsation syntax to you could just initialise it as a List straight away in a similar manner using the Arrays.asList method e.g.:
Then you can do (like above):
STRINGS.contains("the string you want to find");
Just to clear the code up to start with. We have (corrected):
This is a mutable static which FindBugs will tell you is very naughty. It should be private:
(Note, you can actually drop the
new String[];
bit.)So, reference arrays are bad, and in particular here we want a set:
(Paranoid people, such as myself, may feel more at ease if this was wrapped in
Collections.unmodifiableSet
- it could even be made public.)"Given String s, is there a good way of testing whether VALUES contains s?"
O(1).