How to find the index of an int array that matches a specific value

I have

int myArray[]= {12,23,10,22,10}; 

So, I want to get index of 23 from myArray without iterating any loop ( for , while ...).

I would do something like Arrays.asList(myArray).indexOf(23)

This does not work for me. I get -1 as output.

This is working with String[] How

  String myArray[]= {"12","23","10","22","10"}; Arrays.asList(myArray).indexOf("23") 

So why does this not work with int[] ??

+4
source share
4 answers
 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 on objects, so we must use the object type int , since int is a primitive type.

 String myArray[]= {"12","23","10","22","10"}; Arrays.asList(myArray).indexOf("23"); 

In the second case, this will work because String is an object.

When we define a List , define it as List<String> or List<Integer> . therefore primitives are not used in List . Then Arrays.asList(myArray).indexOf("23") find the index of the equivalent object.

+12
source

I agree with Ruchira, and I also want to note that the problem is that int is primitive, and String and Integer are real objects. (note, I would post this as a comment, but I couldn’t reach 50 reputation;))

+4
source

If you want to convert an array of primitives to a list of boxed primitives, use Apache Commons . After you have a list as shown below, use the API in the list to find the object by index.

 List<Integer> list = Arrays.asList(ArrayUtils.toObject(myArray)); 
+2
source

You might consider sorting the array and using a binary division to determine the index. Insertion and search in both cases will be O (log (n)) (instead of O (1) and O (n), respectively).

If you are looking for a lot, you can use a different data structure, such as a hash map, not only for performance, but also because it is easier to write.

+1
source

Source: https://habr.com/ru/post/1496498/


All Articles