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

前端 未结 13 2108
谎友^
谎友^ 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:41

    Testable mockable interafce

    public interface IArrayUtility {
    
        int find(T[] list, T item);
    
    }
    

    implementation

    public class ArrayUtility implements IArrayUtility {
    
        @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);
    }
    

提交回复
热议问题