0

For Python, I can do something like array.index(element) to get the index for an element in array. How can I do this in Java using regular arrays, not arrayList? Is there a similar function?

6 Answers 6

5

You can use Arrays.asList then use List.indexOf. The other suggestions to use Arrays.binarySearch are good but require the array to be sorted.

Sign up to request clarification or add additional context in comments.

Comments

3

You have to use Arrays.binarySearch method (array has to be sorted).

If sorting an array is unacceptable you have only one solution - full scan. Simply loop through the array to find the index of the element. Same can be acheieved by converting array to List using Arrays.asList and then using list's indexOf method.

Comments

1

You can do:

Arrays.asList(regularArray).indexOf(elementYouWant);

or, if the array is sorted, you can use

Arrays.binarySearch();

Comments

1

If you don't want to use Java Collections may can use this. You need implements equals method in your class.

public int index(Object[] array, Object element) {
    for(int i = 0; i < array.lenght; i++) {
        if (array[i] == element) {
            return i;
        }
        if (array[i].equals(element) {
            return i;
        }
    }
    return -1;
}

1 Comment

Better be safe w/ element != null && element.equals(array[i]). (Both null is covered by the 1st if).
1

The best way is writing your own function. each built-in method has issue like need sorted array for binarySearch or creating a new list object for asList method.

Use a method like this.

public int index( int search, int[] arr ){
  for( int i=0; i< arr.length ; i ++ )
    if( arr[ i ] == search)
     return i;
  return -1;
}

Comments

0

There are a couple of ways

1) Arrays.binarySearch

2) or you can loop though and find it.

 public int getArrayIndex(int[] myArray, obj myObject)
{
  int length = Array.getLength(myArray);//get the size of the array
  for (int i = 0; i < lenght; ++i)
   {
     if (myArray[i] == myObject)
      {
        return(i);
      }
    }
   return(-1);//didn't find what I was looking for
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.