如何使用 Java 查找 Arraylist 的最大值及其两个索引位置 [英] How to find the max value of an Arraylist and two of its Index position using Java
本文介绍了如何使用 Java 查找 Arraylist 的最大值及其两个索引位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从带有索引位置的 Arraylist
中找到最大值?
How can I find the maximum value from an Arraylist
with its index positions?
ArrayList ar = new ArrayList();
ar.add(2); // position 0
ar.add(4); // position 1
ar.add(12); // position 2
ar.add(10); // position 3
ar.add(12); // position 4
String obj = Collections.max(ar);
int index = ar.indexOf(obj);
System.out.println("obj max value is " + obj + " and index position is " + index);
上面的程序只是将输出作为第一个具有值12
和索引位置2
的最大对象返回.
The above program just returns the output as the first max object with value 12
and index position 2
.
但我的实际输出应该是索引位置 2
和 4
(因为最大值 12
出现在两个索引位置).>
But my actual output should be index positions 2
and 4
(because max value 12
is present in two index position).
推荐答案
未测试:
public static int maxIndex(List<Integer> list) {
Integer i=0, maxIndex=-1, max=null;
for (Integer x : list) {
if ((x!=null) && ((max==null) || (x>max))) {
max = x;
maxIndex = i;
}
i++;
}
return maxIndex
}
// ...
maxIndex(Arrays.asList(1, 2, 3, 2, 1)); // => 2
maxIndex(Arrays.asList(null, null)); // => -1
maxIndex(new ArrayList<Integer>()); // => -1
这篇关于如何使用 Java 查找 Arraylist 的最大值及其两个索引位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文