To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found. The following illustrates the syntax of the indexOf() method.
ArrayUtils. indexOf(array, element) method finds the index of element in array and returns the index.
Java String indexOf() MethodThe indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.
Javascript arrays cannot have "string indexes". A Javascript Array is exclusively numerically indexed. When you set a "string index", you're setting a property of the object.
Type in:
Arrays.asList(TYPES).indexOf("Sedan");
String carName = // insert code here
int index = -1;
for (int i=0;i<TYPES.length;i++) {
if (TYPES[i].equals(carName)) {
index = i;
break;
}
}
After this index
is the array index of your car, or -1 if it doesn't exist.
for (int i = 0; i < Types.length; i++) {
if(TYPES[i].equals(userString)){
return i;
}
}
return -1;//not found
You can do this too:
return Arrays.asList(Types).indexOf(userSTring);
I had an array of all English words. My array has unique items. But using…
Arrays.asList(TYPES).indexOf(myString);
…always gave me indexOutOfBoundException
.
So, I tried:
Arrays.asList(TYPES).lastIndexOf(myString);
And, it worked. If your arrays don't have same item twice, you can use:
Arrays.asList(TYPES).lastIndexOf(myString);
Use Arrays
class to do this
Arrays.sort(TYPES);
int index = Arrays.binarySearch(TYPES, "Sedan");
try this instead
org.apache.commons.lang.ArrayUtils.indexOf(array, value);
No built-in method. But you can implement one easily:
public static int getIndexOf(String[] strings, String item) {
for (int i = 0; i < strings.length; i++) {
if (item.equals(strings[i])) return i;
}
return -1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With