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

562,295

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();
}
Share:
562,295
Jeomark
Author by

Jeomark

Updated on July 08, 2022

Comments

  • Jeomark
    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
    Admin almost 13 years
    +1 However it should be noted that Arrays.sort mutates the input and the original array will be modified.
  • Jeomark
    Jeomark almost 13 years
    Thanks 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
    Admin almost 13 years
    This 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
    Alex Jones almost 13 years
    Yes it would, you don't have to change anything (but the array type obviously)
  • Jeomark
    Jeomark almost 13 years
    thank you, the 2nd method somehow worked me after adding some logic for duplicate values with different indexes.
  • teloon
    teloon over 11 years
    Actually the code doesn't work. Check Why is indexOf failing to find the object?
  • Leon Helmsley
    Leon Helmsley over 10 years
    You need to convert array to Integer[] instead of int[]. primitive arrays are not autoboxed.
  • Mike Samuel
    Mike Samuel over 10 years
    tab.equals(toSearch) is comparing an array with an int. Maybe tab[i] == toSearch instead.
  • Andre
    Andre over 10 years
    This works thanks Mike... Google for binary search, some nice articles out there and its an interesting method
  • TWiStErRob
    TWiStErRob over 8 years
    The clear and the new ArrayList are unnecessary operations. Allocating a new ArrayList copies the whole array, which is pointless, because Arrays.asList already returns a List which has an indexOf method. Clearing the copy of the list is unnecessary, GC will take it away anyway.
  • TWiStErRob
    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++; VS while ((tab[i] ^ toSearch) != 0) i++;.
  • TWiStErRob
    TWiStErRob over 8 years
    In any case the this way of timing doesn't work, for me bitSearch is always faster than getIndexOf; while if I simply swap the calls to the two methods getIndexOf gets faster than bitSearch. 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
    Langusten Gustel over 7 years
    Is 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
    betontalpfa almost 6 years
    Duplicated answer.
  • Arjun Sunil Kumar
    Arjun Sunil Kumar almost 6 years
    It is Arrays. ie Arrays.asList(array).indexOf(1);
  • double-beep
    double-beep over 4 years
    While 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
    Guillermo Garcia about 4 years
    Great! Thanks for sharing. It helps to learn about the new (optimized) built-in solutions within the language capabilities context.
  • djdance
    djdance over 3 years
    Note, array must be Integer[], not int[]. At least, indexOf() works only with Integer
  • Purushotham CK
    Purushotham CK over 3 years
    This 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
    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
    Simplicity's_Strength about 3 years
    @RyanM That explains the java.util.NoSuchElementException i've had using this code. Well played Sir
  • Hasan Othman
    Hasan Othman over 2 years
    another 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
    Azhar Uddin Sheikh about 2 years
    why can't we use int []