Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, Simplified check if int array contains int

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.

like image 823
Caleb Avatar asked Aug 18 '12 16:08

Caleb


People also ask

How do you check if an int is in an int array Java?

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.

How do you check if an array has integers?

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.

How do you check if an integer array contains a value?

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.

How do you check if an array contains a number?

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.


1 Answers

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); } 
like image 96
Reimeus Avatar answered Sep 29 '22 03:09

Reimeus