Java, Simplified check if int array contains int
You could simply use ArrayUtils.contains
from Apache Commons Lang library.
public boolean contains(final int[] array, final int key) {
return ArrayUtils.contains(array, key);
}
Here is Java 8 solution
public static boolean contains(final int[] arr, final int key) {
return Arrays.stream(arr).anyMatch(i -> i == key);
}
It's because Arrays.asList(array)
returns List<int[]>
. The array
argument is treated as one value you want to wrap (you get a list of arrays of ints), not as vararg.
Note that it does work with object types (not primitives):
public boolean contains(final String[] array, final String key) {
return Arrays.asList(array).contains(key);
}
or even:
public <T> boolean contains(final T[] array, final T key) {
return Arrays.asList(array).contains(key);
}
But you cannot have List<int>
and autoboxing is not working here.
Guava offers additional methods for primitive types. Among them a contains method which takes the same arguments as yours.
public boolean contains(final int[] array, final int key) {
return Ints.contains(array, key);
}
You might as well statically import the guava version.
See Guava Primitives Explained