集册 Java实例教程 返回给定数组中元素的索引。

返回给定数组中元素的索引。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

430
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
返回给定数组中元素的索引。

/*******************************************************************************

 * 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 
 时代Java - nowjava.com**/

//package com.nowjava;


public class Main {

    public static void main(String[] argv) throws Exception {

        Object[] array = new String[] { "1", "abc", "level", null,

                "nowjava.com", "asdf 123" };

        Object element = "nowjava.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");

        }
        /**
         * nowjava 提 供 
        **/

        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]);

          
展开阅读全文