• support@answerspoint.com

How can I test if an array contains a certain value?

2180

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?

2Answer


0
Arrays.asList(yourArray).contains(yourValue)

Warning: this doesn't work for arrays of primitives (see the comments).

  • answered 8 years ago
  • G John

0

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. 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 8 years ago
  • Sandy Hook

Your Answer

    Facebook Share        
       
  • asked 8 years ago
  • viewed 2180 times
  • active 8 years ago

Best Rated Questions