Java Array Index Of indexOf(Object[] elements, Object value)

Here you can find the source of indexOf(Object[] elements, Object value)

Description

Returns the index of the first occurrence of the specified element in this array, or -1 if this list does not contain the element.

License

Apache License

Declaration

public static int indexOf(Object[] elements, Object value) 

Method Source Code

//package com.java2s;
/*//  w w w .j av a  2 s.c  o m
 * Copyright 2010-2012 Roger Kapsi
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

import java.util.List;

public class Main {
    /**
     * Returns the index of the first occurrence of the specified element in 
     * this array, or -1 if this list does not contain the element.
     */
    public static int indexOf(Object[] elements, Object value) {
        int index = 0;
        for (Object element : elements) {
            if (equals(element, value)) {
                return index;
            }
            ++index;
        }
        return -1;
    }

    /**
     * Returns the index of the first occurrence of the specified element in 
     * this {@link Iterable}, or -1 if this list does not contain the element.
     */
    public static int indexOf(Iterable<?> elements, Object value) {
        if (elements instanceof List<?>) {
            return ((List<?>) elements).indexOf(value);
        }

        int index = 0;
        for (Object element : elements) {
            if (equals(element, value)) {
                return index;
            }
            ++index;
        }
        return -1;
    }

    /**
     * Returns {@code true} if the two objects are equal.
     */
    private static boolean equals(Object a, Object b) {
        if (a == null) {
            return b == null;
        }

        return a.equals(b);
    }
}

Related

  1. indexOf(final T[] array, final T value)
  2. indexOf(int[] arr, int e)
  3. indexOf(int[] arr, int val)
  4. indexOf(Object[] array, Object objectToFind)
  5. indexOf(Object[] array, Object objectToFind)
  6. indexOfCS(String[] strings, String a)
  7. indexOfIdentical(Object[] array, Object value)