Java, Simplified check if int array contains int

Caleb picture Caleb · Aug 18, 2012 · Viewed 242.9k times · Source

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.

Answer

Reimeus picture Reimeus · Aug 18, 2012

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);
}