4

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

HybrisHelp
  • 5,518
  • 2
  • 27
  • 65

4 Answers4

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

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
4

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

Jlewis071
  • 175
  • 5
2

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

List<Integer> list = Arrays.asList(ArrayUtils.toObject(myArray));
Andromeda
  • 1,370
  • 2
  • 10
  • 15
1

You can consider keeping your array sorted and use binary subdivision to decide an index. Insert and lookup would both be O(log(n)) in this case (instead of O(1) and O(n) respectively).

If you're doing a lot of looking up you might want to use a different data structure such as a hash map, not just for performance but also because it can be easier to write around.

Ken
  • 30,811
  • 34
  • 116
  • 155