Saturday 4 January 2020

How do I determine whether an array contains a particular value in Java?

Concise update for Java SE 9


Reference arrays are bad. For this case we are after a set. Since Java SE 9 we have Set.of.


private static final Set VALUES = Set.of(
"AB","BC","CD","AE"
);

"Given String s, is there a good way of testing whether VALUES contains s?"


VALUES.contains(s)

O(1).


The right type, immutable, O(1) and concise. Beautiful.*


Original answer details


Just 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. Do not modify statics and do not allow other code to do so also. At an absolute minimum, the field should be private:


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

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


Reference arrays are still bad and we want a set:


private static final Set VALUES = new HashSet(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 then even be made public.)


(*To be a little more on brand, the collections API is predictably still missing immutable collection types and the syntax is still far too verbose, for my tastes.)

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...