Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the index of an element in an int array?

How can I find an index of a certain value in a Java array of type int?

I tried using Arrays.binarySearch on my unsorted array, it only sometimes gives the correct answer.

like image 263
Jeomark Avatar asked May 30 '11 01:05

Jeomark


People also ask

How do you find the index of an integer in an array?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.

How do you find the index of an object in an array?

To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.

Can you use indexOf on INT?

int indexOf(int ch) : It returns the index of the first occurrence of character ch in a given String. int indexOf(int ch, int fromIndex) : It returns the index of first occurrence of character ch in the given string after the specified index “fromIndex”. For example, if the indexOf() method is called like this str.

How do you find the index of an element?

To find the index of an element in a list, you use the index() function. It returns 3 as expected.


1 Answers

Integer[] array = {1,2,3,4,5,6};  Arrays.asList(array).indexOf(4); 

Note that this solution is threadsafe because it creates a new object of type List.

Also you don't want to invoke this in a loop or something like that since you would be creating a new object every time

like image 71
Pablo Fernandez Avatar answered Sep 23 '22 18:09

Pablo Fernandez