首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何从列表/ArrayList中获取最大值?

如何从列表/ArrayList中获取最大值?
EN

Stack Overflow用户
提问于 2018-03-21 01:58:27
回答 2查看 0关注 0票数 0

有一个存储整数值的ArrayList。我需要在这个列表中找到最大值。例如,假设arrayList存储的值是:10, 20, 30, 40, 50并且最大值是50

找到最大值的有效方法是什么?

@编辑:我刚刚找到了一个我不太确定的解决方案

代码语言:javascript
复制
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

EN

Stack Overflow用户

发布于 2018-03-21 11:22:46

这个问题已经有将近一年的历史了,但是我发现如果你为对象做了一个自定义比较器,可以使用Collection s.max来表示对象的数组列表。

代码语言:txt
复制
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());
票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100003649

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档