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.
We can use the contains() method to find the specified value in the given array. This method returns a boolean value either true or false . It takes two arguments; the first is an array, and the second is the value to find.
To check if an array contains only numbers:Call the every() method, passing it a function. On each iteration, check if the type of of the current element is number . The every method returns true , only if the condition is met for every array element.
Using List contains() method. We can use Arrays class to get the list representation of the array. Then use the contains() method to check if the array contains the value.
For primitive values, use the array. includes() method to check if an array contains a value. For objects, use the isEqual() helper function to compare objects and array. some() method to check if the array contains the object.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With