javalist最⼤值索引,如何使⽤Java查Arraylist的最⼤值及其两
个Index位置
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);
The above program just returns the output as the first max object with value 12 and index position 2.
But my actual output should be index positions 2 and 4 (because max value 12 is present in two index position).
解决⽅案
Untested:
public static int maxIndex(List list) {
Integer i=0, maxIndex=-1, max=null;
java中index是什么意思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()); // => -1

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。