如何使用Java查找Arraylist的最大值及其两个Index位置 [英] How to find the max value of an Arraylist and two of its Index position using Java

查看:818
本文介绍了如何使用Java查找Arraylist的最大值及其两个Index位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从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.

但是我的实际输出应该是索引位置24(因为最大值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的最大值及其两个Index位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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