How to find index of STRING array in Java from a given value?

前端 未结 13 2058
谎友^
谎友^ 2020-12-08 02:11

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 :

<
相关标签:
13条回答
  • 2020-12-08 02:40

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

    0 讨论(0)
  • 2020-12-08 02:41

    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);
    }
    
    0 讨论(0)
  • 2020-12-08 02:41

    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")
    
    0 讨论(0)
  • 2020-12-08 02:42

    try this instead

    org.apache.commons.lang.ArrayUtils.indexOf(array, value);
    
    0 讨论(0)
  • 2020-12-08 02:43

    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
          }
    
    0 讨论(0)
  • 2020-12-08 02:45
    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.

    0 讨论(0)
提交回复
热议问题