【问题标题】:Find an object inside ArrayList Java在 ArrayList Java 中查找对象
【发布时间】:2013-10-12 05:21:52
【问题描述】:

我有一个对象的 ArrayList。每个对象都是 Player 类型(我拥有的类之一)。 每个 Player 对象都有一个 getName() 方法和一个 getValue() 方法。 getValue 方法是整数类型。 所有的 Player 对象都进入一个 ArrayList,listOfPlayers。 如何找到具有最高 getValue() 的 PLayer 对象?

我知道有一个名为 Collections.max() 的方法,但对我来说,它似乎只有在 ArrayList 充满整数时才有效。

谢谢

【问题讨论】:

  • 使用比较器,对列表进行排序,检索第一个元素。遍历所有元素并获得最高的元素。
  • 如果只需要找到一次,只需进行线性搜索。

标签: java collections arraylist


【解决方案1】:

将max() 与比较器一起使用

Collection.max(collection, customComparator);

另见

【讨论】:

    【解决方案2】:

    你需要像这样为你的类实现比较器

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

    然后调用

      Collections.max(listOfPlayers, cmp);
    

    【讨论】:

      猜你喜欢
      • 2018-06-13
      • 1970-01-01
      • 2018-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-23
      • 2020-10-27
      • 2015-01-11
      相关资源
      最近更新 更多