I was wondering if it was better to have a method for this and pass the Array
to that method or to write it out every time I want to check if a number is in the array
.
For example:
public static boolean inArray(int[] array, int check) { for (int i = 0; i < array.length; i++) { if (array[i] == check) return true; } return false; }
Thanks for the help in advance!
Iterating over an array You can iterate over an array using for loop or forEach loop. Using the for loop − Instead on printing element by element, you can iterate the index using for loop starting from 0 to length of the array (ArrayName. length) and access elements at each index.
How to Loop Through an Array with a forEach Loop in JavaScript. The array method forEach() loop's through any array, executing a provided function once for each array element in ascending index order. This function is known as a callback function.
The most common iterator in JavaScript is the Array iterator, which returns each value in the associated array in sequence. While it is easy to imagine that all iterators could be expressed as arrays, this is not true. Arrays must be allocated in their entirety, but iterators are consumed only as necessary.
ArrayList forEach() method in JavaThe forEach() method of ArrayList used to perform the certain operation for each element in ArrayList. This method traverses each element of the Iterable of ArrayList until all elements have been Processed by the method or an exception is raised.
Since atleast Java 1.5.0 (Java 5) the code can be cleaned up a bit. Array
s and anything that implements Iterator
(e.g. Collection
s) can be looped as such:
public static boolean inArray(int[] array, int check) { for (int o : array){ if (o == check) { return true; } } return false; }
In Java 8 you can also do something like:
// import java.util.stream.IntStream; public static boolean inArray(int[] array, int check) { return IntStream.of(array).anyMatch(val -> val == check); }
Although converting to a stream for this is probably overkill.
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