Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find index of int array which match specific value [duplicate]

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[] ? ?

like image 923
HybrisHelp Avatar asked Dec 01 '22 03:12

HybrisHelp


2 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 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.

like image 71
Ruchira Gayan Ranaweera Avatar answered Dec 04 '22 10:12

Ruchira Gayan Ranaweera


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 ;) )

like image 37
Jlewis071 Avatar answered Dec 04 '22 11:12

Jlewis071