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

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 ?


Arrays.asList(yourArray).contains(yourValue)

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


Since java-8

You can now use a Stream to check whether an array of int , double or long contains a value (by respectively using a IntStream , DoubleStream or LongStream )

Example

int[] a = {1,2,3,4};
boolean contains = IntStream.of(a).anyMatch(x -> x == 4);

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).


You can use ArrayUtils.contains from Apache Commons Lang

public static boolean contains(Object[] array, Object objectToFind)

Note that this method returns false if the passed array is null .

There are also methods available for primitive arrays of all kinds.

Example:

String[] fieldsToInclude = { "id", "name", "location" };

if ( ArrayUtils.contains( fieldsToInclude, "id" ) ) {
    // Do some stuff.
}
链接地址: http://www.djcxy.com/p/13834.html

上一篇: Android:ActionBar,TabListener和support.v4.Fragment

下一篇: 我如何测试数组是否包含某个值?