如何从Arraylist带有索引位置的 a 中找到最大值?
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);
Run Code Online (Sandbox Code Playgroud)
上面的程序只是将输出作为第一个具有 value12和 index position 的max 对象返回2。
但我的实际输出应该是索引位置2和4(因为最大值12出现在两个索引位置)。
您可以使用集合查找列表的最大值,然后使用属性indexOf查找其在列表中的位置。
List<Integer> myList = new ArrayList<Integer>();
myList.add(3); // adding some values
myList.add(5);
myList.add(7);
myList.add(3);
myList.add(1);
Integer maxVal = Collections.max(myList); // should return 7
Integer maxIdx = myList.indexOf(maxVal); // should return 2 (position of the value 7)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25125 次 |
| 最近记录: |