I have
int myArray[]= {12,23,10,22,10};
So i want to get index of 23 from myArray with out iterating any loop (for ,while ...) .
I would do something like Arrays.asList(myArray).indexOf(23)
This is not work for me . I get -1 as output .
This is work with String[]
Like
String myArray[]= {"12","23","10","22","10"};
Arrays.asList(myArray).indexOf("23")
So why this is not working with int[] ? ?
Integer myArray[]= {12,23,10,22,10};
System.out.println(Arrays.asList(myArray).indexOf(23));
will solve the problem
Arrays.asList(myArray).indexOf(23) this search about objects so we have to use object type of int since int is primitive type.
String myArray[]= {"12","23","10","22","10"};
Arrays.asList(myArray).indexOf("23");
In second case this will work because String is object.
When we define a List,We define it as List<String> or List<Integer>. so primitives are not use in List. Then Arrays.asList(myArray).indexOf("23") find index of equivalent Object.
I concur with Ruchira, and also want to point out that the problem has to do with the fact that int is a primitive while String and Integer are actual objects. (note I would have posted this as a comment but can't until 50 reputation ;) )
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