问题
有一个存储整数值的ArrayList。我需要在此列表中找到最大值。例如。假设arrayList存储的值为:10, 20, 30, 40, 50
,最大值为50
。
找到最大值的有效方法是什么?
@Edit:我刚刚找到了一个我不太确定的解决方案
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 binary sort algorithm
#1 热门回答(228 赞)
你可以使用Collections API
轻松实现你想要的 - 高效读取 - 足够2902144
Collections.max(arrayList);
根据元素的自然顺序返回给定集合的最大元素。集合中的所有元素都必须实现Comparable接口。
#2 热门回答(24 赞)
这个问题差不多用了一年,但我发现如果你为对象创建一个自定义比较器,你可以使用Collections.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());
#3 热门回答(15 赞)
public int getMax(ArrayList list){
int max = Integer.MIN_VALUE;
for(int i=0; i<list.size(); i++){
if(list.get(i) > max){
max = list.get(i);
}
}
return max;
}
根据我的理解,这基本上是Collections.max()所做的,尽管它们使用比较器,因为列表是通用的。