Check only for the first index

For an array of primitives, the simplest implementation speaks for itself:

public static int findIndexOfElement(int[] arr, int toFind) {

for (int i = 0; i < arr.length; i++) {
if (arr[i] == toFind) {
return i;
}
}

return -1;
}

Relying on Java 8 functional style, we can try to loop the array and filter the elements that match the given element. In the end, simply return the first found element:

public static int findIndexOfElement(int[] arr, int toFind) {

return IntStream.range(0, arr.length)
.filter(i -> toFind == arr[i])
.findFirst()
.orElse(-1);
}

For an array of Object, there are at least three approaches. In the first instance, we can rely on the equals() contract:

public static <T> int findIndexOfElementObject(T[] arr, T toFind) {

for (int i = 0; i < arr.length; i++) {
if (arr[i].equals(toFind)) {
return i;
}
}

return -1;
}
Similarly, we can rely on Arrays.asList(arr).indexOf(find). Basically, convert the array to a List and call the indexOf() method. Behind the scenes, this method uses the equals() contract.

Secondly, we can rely on a Comparator:

public static <T> int findIndexOfElementObject(
T[] arr, T toFind, Comparator<? super T> c) {

for (int i = 0; i < arr.length; i++) {
if (c.compare(arr[i], toFind) == 0) {
return i;
}
}

return -1;
}

And thirdly, we can rely on Java 8 functional style and a Comparator:

public static <T> int findIndexOfElementObject(
T[] arr, T toFind, Comparator<? super T> c) {

return IntStream.range(0, arr.length)
.filter(i -> c.compare(toFind, arr[i]) == 0)
.findFirst()
.orElse(-1);
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.44.53