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
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
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
element != null && element.equals(array[i]). (Both null is covered by the 1st if).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
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
}