Basically my mate has been saying that I could make my code shorter by using a different way of checking if an int array contains an int, although he won’t tell me what it is :P.
Current:
public boolean contains(final int[] array, final int key) {
for (final int i : array) {
if (i == key) {
return true;
}
}
return false;
}
Have also tried this, although it always returns false for some reason.
public boolean contains(final int[] array, final int key) {
return Arrays.asList(array).contains(key);
}
Could anyone help me out?
Thank you.
It’s because
Arrays.asList(array)returnsList<int[]>. Thearrayargument 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):
or even:
But you cannot have
List<int>and autoboxing is not working here.