Java tutorial
//package com.java2s; /* * 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); } }