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

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

Description

Returns the index of the last 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 lastIndexOf(Object[] elements, Object value) 

Method Source Code

//package com.java2s;
/*/*from w ww.ja  va 2  s .co 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 last occurrence of the specified element in 
     * this array, or -1 if this list does not contain the element.
     */
    public static int lastIndexOf(Object[] elements, Object value) {
        for (int i = elements.length - 1; i >= 0; --i) {
            if (equals(elements[i], value)) {
                return i;
            }
        }
        return -1;
    }

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

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

    /**
     * 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. lastIndexOf(int[] array, int intToFind)
  2. lastIndexOf(int[] array, int valueToFind)
  3. lastIndexOf(Object o, Object[] vals)
  4. lastIndexOf(Object[] array, Object object)
  5. lastIndexOf(Object[] array, Object objectToFind)
  6. lastIndexOf(String source, char[] chars)
  7. lastIndexOf(String str, String[] path)
  8. lastIndexOf(T[] array, T valueToFind, int startIndex)
  9. lastIndexOfAny(byte[] values, byte[] array)