سؤال

I wanted to know if there's a native method in array for Java to get the index of the table for a given value ?

Let's say my table contains these strings :

public static final String[] TYPES = {
        "Sedan",
        "Compact",
        "Roadster",
        "Minivan",
        "SUV",
        "Convertible",
        "Cargo",
        "Others"
    };

Let's say the user has to enter the type of car and that then in the background the program takes that string and get's it's position in the array.

So if the person enters : Sedan It should take the position 0 and store's it in the object of Cars created by my program ...

هل كانت مفيدة؟

المحلول 2

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.

نصائح أخرى

Type in:

Arrays.asList(TYPES).indexOf("Sedan");
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);

try this instead

org.apache.commons.lang.ArrayUtils.indexOf(array, value);

Use Arrays class to do this

Arrays.sort(TYPES);
int index = Arrays.binarySearch(TYPES, "Sedan");

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

There is no native indexof method in java arrays.You will need to write your own method for this.

An easy way would be to iterate over the items in the array in a loop.

for (var i = 0; i < arrayLength; i++) {
 // (string) Compare the given string with myArray[i]
 // if it matches store/save i and exit the loop.
}

There would definitely be better ways but for small number of items this should be blazing fast. Btw this is javascript but same method should work in almost every programming language.

Try this Function :

public int indexOfArray(String input){
     for(int i=0;i<TYPES,length();i++)
       {
         if(TYPES[i].equals(input))
         {
          return i ;
         }
        }
      return -1     // if the text not found the function return -1
      }

Testable mockable interafce

public interface IArrayUtility<T> {

    int find(T[] list, T item);

}

implementation

public class ArrayUtility<T> implements IArrayUtility<T> {

    @Override
    public int find(T[] array, T search) {
        if(array == null || array.length == 0 || search == null) {
            return -1;
        }

        int position = 0;

        for(T item : array) {

            if(item.equals(search)) {
                return position;
            } else {
                ++position;
            }
        }

        return -1;
    }

}

Test

@Test
public void testArrayUtilityFindForExistentItemReturnsPosition() {
    // Arrange
    String search = "bus";
    String[] array = {"car", search, "motorbike"};

    // Act
    int position = arrayUtility.find(array, search);

    // Assert
    Assert.assertEquals(position, 1);
}

Use this as a method with x being any number initially. The string y being passed in by console and v is the array to search!

public static int getIndex(int x, String y, String[]v){
    for(int m = 0; m < v.length; m++){
        if (v[m].equalsIgnoreCase(y)){
            x = m;
        }
    }
    return x;
}

Refactoring the above methods and showing with the use:

private String[] languages = {"pt", "en", "es"};
private Integer indexOf(String[] arr, String str){
   for (int i = 0; i < arr.length; i++)
      if(arr[i].equals(str)) return i;
   return -1;
}
indexOf(languages, "en")
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top