How to find the index of an element in an int array?
Solution 1
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
Solution 2
Another option if you are using Guava Collections is Ints.indexOf
// Perfect storm:
final int needle = 42;
final int[] haystack = [1, 2, 3, 42];
// Spoiler alert: index == 3
final int index = Ints.indexOf(haystack, needle);
This is a great choice when space, time and code reuse are at a premium. It is also very terse.
Solution 3
A look at the API and it says you have to sort the array first
So:
Arrays.sort(array);
Arrays.binarySearch(array, value);
If you don't want to sort the array:
public int find(double[] array, double value) {
for(int i=0; i<array.length; i++)
if(array[i] == value)
return i;
}
Solution 4
Copy this method into your class
public int getArrayIndex(int[] arr,int value) {
int k=0;
for(int i=0;i<arr.length;i++){
if(arr[i]==value){
k=i;
break;
}
}
return k;
}
Call this method with pass two perameters Array and value and store its return value in a integer variable.
int indexNum = getArrayIndex(array,value);
Thank you
Solution 5
You can use modern Java to solve this problem. Please use the code below:
static int findIndexOf(int V, int[] arr) {
return IntStream.range(0, arr.length)
.filter(i->arr[i]==V)
.findFirst()
.getAsInt();
}
Jeomark
Updated on July 08, 2022Comments
-
Jeomark almost 2 years
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. -
Admin almost 13 years+1 However it should be noted that
Arrays.sort
mutates the input and the original array will be modified. -
Jeomark almost 13 yearsThanks but would it work for type double? Sorry i forgot to mention in the question, but i need to work this for double values as well. It works fine with ints though.
-
Admin almost 13 yearsThis is one way, yes. However it is not the only way. The use of the boolean variable
found
here is useless (and not used) and should be removed. A +1 for showing "the manual loop method" though (stylistic and formatting issues aside). -
Alex Jones almost 13 yearsYes it would, you don't have to change anything (but the array type obviously)
-
Jeomark almost 13 yearsthank you, the 2nd method somehow worked me after adding some logic for duplicate values with different indexes.
-
teloon over 11 yearsActually the code doesn't work. Check Why is indexOf failing to find the object?
-
Leon Helmsley over 10 yearsYou need to convert array to Integer[] instead of int[]. primitive arrays are not autoboxed.
-
Mike Samuel over 10 years
tab.equals(toSearch)
is comparing an array with an int. Maybetab[i] == toSearch
instead. -
Andre over 10 yearsThis works thanks Mike... Google for binary search, some nice articles out there and its an interesting method
-
TWiStErRob over 8 yearsThe
clear
and thenew ArrayList
are unnecessary operations. Allocating a newArrayList
copies the whole array, which is pointless, becauseArrays.asList
already returns aList
which has anindexOf
method. Clearing the copy of the list is unnecessary, GC will take it away anyway. -
TWiStErRob over 8 years@Andre if you're trying to prove a point give them a level playing field (same order, same control flow):
while (tab[i] != toSearch) i++;
VSwhile ((tab[i] ^ toSearch) != 0) i++;
. -
TWiStErRob over 8 yearsIn any case the this way of timing doesn't work, for me
bitSearch
is always faster thangetIndexOf
; while if I simply swap the calls to the two methodsgetIndexOf
gets faster thanbitSearch
. This clearly demonstrates that the second one is always faster for some reason of JVM internals. You should be repeating the experiment many times (probably millions), averaging the values, discarding extreme values and doing a warmup that is very similar to the test. -
Langusten Gustel over 7 yearsIs this really threadsafe? When I click through the source the List.asList() creates an ArrayList that is taking the the int array directly as data container (not copying)
-
betontalpfa almost 6 yearsDuplicated answer.
-
Arjun Sunil Kumar almost 6 yearsIt is Arrays. ie Arrays.asList(array).indexOf(1);
-
double-beep over 4 yearsWhile this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.
-
Guillermo Garcia about 4 yearsGreat! Thanks for sharing. It helps to learn about the new (optimized) built-in solutions within the language capabilities context.
-
djdance over 3 yearsNote, array must be Integer[], not int[]. At least, indexOf() works only with Integer
-
Purushotham CK over 3 yearsThis will not work if primitive int type is a type an array. In case of primitive array type, box it before using: List<Integer> list = IntStream.of(array) .boxed() .collect(Collectors.toList()); Then, Arrays.asList(array).indexOf(4); will give the correct index.
-
Ryan M about 3 years@Simplicity's_Strength Your edit was half correct, half incorrect. Arrays do start at 0, but the second parameter to
range
is exclusive. Good catch on that first bug, though. -
Simplicity's_Strength about 3 years@RyanM That explains the
java.util.NoSuchElementException
i've had using this code. Well played Sir -
Hasan Othman over 2 yearsanother use case, what if the array has two 4? mean like this {1,2,3,4,5,4,6} , how to get the both indexs fast and clean?
-
Azhar Uddin Sheikh about 2 yearswhy can't we use
int []