集册 Java实例教程 获取最大数组项的索引。

获取最大数组项的索引。

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

462
获取最大数组项的索引。


//package com.nowjava;


public class Main {//时 代 J a v a - nowjava.com 提供

    /**

     * Get the index of the array item which is maximum.

     * 

     * @param <T>

     * @param array

     * @return index of the maximum

     */

    public static <T extends Comparable<T>> int getIndexOfMax(T[] array) {

        int indexOfMax = -1;

        T max = array[0];

        for (int i = 0; i < array.length; i++) {

            if (array[i].compareTo(max) > 0) {

                indexOfMax = i;

                max = array[i];

            }

        }

        return indexOfMax;//N o w J a v a . c o m 提 供

    }


    /**

     * Get the index of the array item which is maximum.

     * 

     * @param array

     * @return index of the maximum

     */

    public static int getIndexOfMax(int[] array) {

        if (array.length <= 1) {

            return 1;

        }

        int indexOfMax = 0;

        int max = array[0];

        for 
展开阅读全文