Find the index of a value inside an array. - Java Collection Framework

Java examples for Collection Framework:Array Search

Description

Find the index of a value inside an array.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        Object[] array = new String[] { "1", "abc", "level", null,
                "java2s.com", "asdf 123" };
        Object value = "java2s.com";
        System.out.println(findIndex(array, value));
    }/*from ww w  .  j  av  a 2s.  c  o  m*/

    /**
     * Find the index of a value inside an array. If not found, or any of the param is null, return -1
     * @param array The array to lookup the value (if null, return -1)
     * @param value The value to lookup (if null, return -1)
     * @return the index of the match value, or -1 is not found
     */
    public static int findIndex(Object[] array, Object value) {
        if (array == null || value == null) {
            return -1;
        }
        int i = 0;
        for (Object obj : array) {
            if (obj.equals(value)) {
                return i;
            }
            i++;
        }
        return -1;
    }
}

Related Tutorials