简体   繁体   中英

Java array analog for python list.index()?

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?

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.

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.

You can do:

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

or, if the array is sorted, you can use

Arrays.binarySearch();

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

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

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
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM