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));
4
  • 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?? Commented Feb 20, 2018 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? Commented Feb 20, 2018 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. Commented Feb 20, 2018 at 11:48
  • Please ask question carefully. What do you want to find index of number or index of array. Commented Feb 20, 2018 at 11:48

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

I'd like downvoters to let me know what they do not agree with !
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.