Java Collection Search indexOf(final Collection c, final Object elem)

Here you can find the source of indexOf(final Collection c, final Object elem)

Description

Get the index position of an element in a collection

License

Open Source License

Parameter

Parameter Description
c The Collection.
elem the element to find the index of

Return

the element index

Declaration

public static int indexOf(final Collection c, final Object elem) 

Method Source Code

//package com.java2s;
/* $Id$/*w  w  w .j  a v  a 2s.  co m*/
 *******************************************************************************
 * Copyright (c) 2009 Contributors - see below
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Bob Tarling
 *******************************************************************************
 */

import java.util.Collection;
import java.util.List;

public class Main {
    /**
     * Get the index position of an element in a collection
     *
     * @param c The Collection.
     * @param elem the element to find the index of
     * @return the element index
     */
    public static int indexOf(final Collection c, final Object elem) {
        if (c instanceof List) {
            return ((List) c).indexOf(elem);
        } else {
            int index = 0;
            for (Object element : c) {
                if (element == elem) {
                    return index;
                } else {
                    ++index;
                }
            }
            return -1;
        }
    }
}

Related

  1. hasOneItem(final Collection col)
  2. hasOtherThan(Collection a, Collection b)
  3. hasValidElement(Collection collection)
  4. hasValue(Collection collection)
  5. indexOf(Collection stringCollection, String str)
  6. indexOfInstance(final Collection collection, final T instance)
  7. indexOfObjectIdentity(Collection collection, Object object)