如何找到一个ArrayList的最小值,指数号一起? (JAVA) [英] How to find the minimum value in an ArrayList, along with the index number? (Java)

查看:1100
本文介绍了如何找到一个ArrayList的最小值,指数号一起? (JAVA)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在我的Java ArrayList中的最小值的索引值。 MY ArrayList中拥有几个花车,和我试图想办法,我可以得到的最小浮动的索引号,所以我可以在我的code在其他地方使用该索引号。我是一个初学者,所以请不要恨我。谢谢!

I need to get the index value of the minimum value in my arraylist in Java. MY arraylist holds several floats, and I'm trying to think of a way I can get the index number of the smallest float so I can use that index number elsewhere in my code. I'm a beginner, so please don't hate me. Thanks!

推荐答案

您可以使用<一个href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#min%28java.util.Collection%29\">Collections.min和<一个href=\"http://docs.oracle.com/javase/7/docs/api/java/util/List.html#indexOf%28java.lang.Object%29\">List.indexOf:

int minIndex = list.indexOf(Collections.min(list));

如果你想遍历列表只有一次(以上可以遍历两次):

If you want to traverse the list only once (the above may traverse it twice):

public static <T extends Comparable<T>> int findMinIndex(final List<T> xs) {
    int minIndex;
    if (xs.isEmpty()) {
        minIndex = -1;
    } else {
        final ListIterator<T> itr = xs.listIterator();
        T min = itr.next(); // first element as the current minimum
        minIndex = itr.previousIndex();
        while (itr.hasNext()) {
            final T curr = itr.next();
            if (curr.compareTo(min) < 0) {
                min = curr;
                minIndex = itr.previousIndex();
            }
        }
    }
    return minIndex;
}

这篇关于如何找到一个ArrayList的最小值,指数号一起? (JAVA)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆