Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/160.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在ArrayList Java中查找对象_Java_Collections_Arraylist - Fatal编程技术网

在ArrayList Java中查找对象

在ArrayList Java中查找对象,java,collections,arraylist,Java,Collections,Arraylist,我有一个对象的数组列表。每个对象都是我拥有的一个类的类型。 每个播放器对象都有一个getName方法和一个getValue方法。getValue方法是整数类型。 所有玩家对象都进入一个ArrayList,listOfPlayers。 如何找到具有最高getValue的PLayer对象 我知道有一个名为Collections.max的方法,但对我来说,只有在ArrayList中满是整数时,它才起作用 感谢使用比较仪 Collection.max(collection, customComparat

我有一个对象的数组列表。每个对象都是我拥有的一个类的类型。 每个播放器对象都有一个getName方法和一个getValue方法。getValue方法是整数类型。 所有玩家对象都进入一个ArrayList,listOfPlayers。 如何找到具有最高getValue的PLayer对象

我知道有一个名为Collections.max的方法,但对我来说,只有在ArrayList中满是整数时,它才起作用

感谢使用比较仪

Collection.max(collection, customComparator);
也看到


您需要像这样为类实现Comparator

Comparator<Player> cmp = new Comparator<Player>() {
    @Override
    public int compare(Player o1, Player o2) {
        return Integer.valueOf(o1.getValue()).compareTo(Integer.valueOf(o2.getValue()));
    }
};

使用比较器,对列表排序,检索第一个元素。迭代所有元素并获得最高值的元素,.java.util.Comparatori如果只需查找一次,只需进行线性搜索。
  Collections.max(listOfPlayers, cmp);