Organizational Research By

Surprising Reserch Topic

In Java, how can I test if an Array contains a certain value?



asked May 15, 2015 in Core java by rajesh
0 votes
24 views



Related Hot Questions

2 Answers

0 votes
Arrays.asList(yourArray).contains(yourValue)
answered May 15, 2015 by rajesh
0 votes

ust to clear the code up to start with. We have (corrected):

public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};

This is a mutable static which FindBugs will tell you is very naughty. It should be private:

private static final String[] VALUES = new String[] {"AB","BC","CD","AE"};

(Note, you can actually drop the new String[]; bit.)

So, reference arrays are bad, and in particular here we want a set:

private static final Set<String> VALUES = new HashSet<String>(Arrays.asList(
     new String[] {"AB","BC","CD","AE"}
));

(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?"

VALUES.contains(s)

O(1).

answered May 15, 2015 by rajesh

...