有一个存储整数值的ArrayList。我需要在这个列表中找到最大值。例如,假设arrayList存储的值是:10, 20, 30, 40, 50
并且最大值是50
。
找到最大值的有效方法是什么?
@编辑:我刚刚找到了一个我不太确定的解决方案
ArrayList<Integer> arrayList = new ArrayList<Integer>();
arrayList.add(100); /* add(200), add(250) add(350) add(150) add(450)*/
Integer i = Collections.max(arrayList)
并且这返回最大值。
比较每个值的另一种方法,例如 selection sort or binaray sort algorithm
发布于 2018-03-21 10:33:09
你可以使用它,Collections API
轻松实现你想要的功能 -
Collections.max(arrayList);
根据元素的自然顺序返回给定集合的最大元素。集合中的所有元素都必须实现Comparable接口。
发布于 2018-03-21 11:22:46
这个问题已经有将近一年的历史了,但是我发现如果你为对象做了一个自定义比较器,可以使用Collection s.max来表示对象的数组列表。
import java.util.Comparator;
public class compPopulation implements Comparator<Country> {
public int compare(Country a, Country b) {
if (a.getPopulation() > b.getPopulation())
return -1; // highest value first
if (a.getPopulation() == b.Population())
return 0;
return 1;
}
}
ArrayList<Country> X = new ArrayList<Country>();
// create some country objects and put in the list
Country ZZ = Collections.max(X, new compPopulation());
https://stackoverflow.com/questions/-100003649
复制相似问题