1

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));
Salem
  • 13,516
  • 4
  • 51
  • 70
krishna veer
  • 474
  • 1
  • 4
  • 16
  • 1
    Your question is poorly structured, but from what I managed to understand why dont you just use `array[indexNumber]` to print the element at that index?? – N. Ivanov Feb 20 '18 at 11:42
  • "at position 14" - `indexOf` returns the location _of_ the first occurrence of this value, not the element _at_ that index. If you are using arrays why do you not use the `[]` operator? Or did you mean something else? – Salem Feb 20 '18 at 11:44
  • it is unclear if you want the value at position 14, or if you want the position of value 14. In first case you should use veer[14], in second case, you should use a for loop to cycle through the array elements. In either case you don't need to convert the array to a list. – João Gonçalves Feb 20 '18 at 11:48
  • Please ask question carefully. What do you want to find index of number or index of array. – Vishal Kawade Feb 20 '18 at 11:48

2 Answers2

7

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[]).

Betlista
  • 10,327
  • 13
  • 69
  • 110
0

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)

Sasikumar Murugesan
  • 4,412
  • 10
  • 51
  • 74