i am trying to use this function but it is giving that index is -1. so what can i do
int[] veer = {14,25,14,56,15,36,56,77,18,29,49};
int a = Arrays.asList(veer).indexOf(14);
System.out.println("my array at position 14 is :" + (a));
i am trying to use this function but it is giving that index is -1. so what can i do
int[] veer = {14,25,14,56,15,36,56,77,18,29,49};
int a = Arrays.asList(veer).indexOf(14);
System.out.println("my array at position 14 is :" + (a));
I assume, you want to learn/test what indexOf
is doing. The problem is, that Arrays.asList(veer)
returns list containing one element - whole array.
When I split the code to multiple lines, it is doing:
int[] orig = {14,25,14,56,15,36,56,77,18,29,49};
List<int[]> origList = Arrays.asList(orig);
and that's why, your indexOf is not able to find 14 in a list, because simply said, there is no integer in list.
When you use wrapper type, it works as you might expect
Integer[] veer = {14,25,14,56,15,36,56,77,18,29,49};
List<Integer> list = Arrays.asList(veer);
int a = list.indexOf(25); // I changed to 25
System.out.println("my array at position 25 is :" + a);
which prints index 1.
To learn about wrapping/unwrapping array, you can read more here Converting Array of Primitives to Array of Containers in Java but changing int[]
to Integer[]
is simplest in this case (you are not forced by API to accept int[]
).
In your code
int[] veer = {14,25,14,56,15,36,56,77,18,29,49};
to
Integer[] veer = {14,25,14,56,15,36,56,77,18,29,49};
because indexOf
expect a object
type since it is primitive it is return as -1(-1 represents not found)