The following code in Java return -1. I thought that it should return 3.
int[] array = {1,2,3,4,5,6};
System.out.println(Arrays.asList(array).indexOf(4));
Can you help me understand how this function works.
Thanks
ArrayUtils. indexOf(array, element) method finds the index of element in array and returns the index.
To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.
There is no indexOf() method for an array in Java, but an ArrayList comes with this method that returns the index of the specified element. To access the indexOf() function, we first create an array of Integer and then convert it to a list using Arrays. asList() .
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on 1st index and so on. Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use the sizeof operator.
Before Java 5, Arrays.asList
used to accept an Object[]
. When generics and varargs were introduced into the language this was changed to
public static <T> List<T> asList(T... arr)
In your example, T
cannot be int
because int
is a primitive type. Unfortunately, the signature matches with T
equal to int[]
instead, which is a reference type. The result is that you end up with a List
containing an array, not a List
of integers.
In Java 4, your code would not have compiled because an int[]
is not an Object[]
. Not compiling is preferable to producing a strange result, and in Effective Java, Josh Bloch says retrofitting asList
to be a varargs method was a mistake.
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