Returns the index of an element in a given array. - Java Collection Framework

Java examples for Collection Framework:Array Element

Description

Returns the index of an element in a given array.

Demo Code

/*******************************************************************************
 * Copyright 2014 uniVocity Software Pty Ltd
 *
 * 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.//from w w  w  .  ja  v  a  2 s  .  com
 ******************************************************************************/
//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        Object[] array = new String[] { "1", "abc", "level", null,
                "java2s.com", "asdf 123" };
        Object element = "java2s.com";
        System.out.println(indexOf(array, element));
    }

    /**
     * Returns the index of an element in a given array.
     * @param array the element array
     * @param element the element to be looked for in the array.
     *
     * @return the index of the given element in the array, or -1 if the element could not be found.
     */
    public static int indexOf(Object[] array, Object element) {
        if (array == null) {
            throw new NullPointerException("Null array");
        }
        if (element == null) {
            for (int i = 0; i < array.length; i++) {
                if (array[i] == null) {
                    return i;
                }
            }
        } else {
            if (element instanceof String && array instanceof String[]) {
                for (int i = 0; i < array.length; i++) {
                    String e = String.valueOf(array[i]);
                    if (element.toString().equalsIgnoreCase(e)) {
                        return i;
                    }
                }
            }

            for (int i = 0; i < array.length; i++) {
                if (element.equals(array[i])) {
                    return i;
                }
            }
        }
        return -1;
    }
}

Related Tutorials