【问题标题】:How to find the minimum and maximum in a ArrayList<Entry> using Java如何使用 Java 在 ArrayList<Entry> 中找到最小值和最大值
【发布时间】:2015-11-25 11:10:30
【问题描述】:

我正在尝试找到一个的最小值和最大值

ArrayList<Entry>

例如,我的 ArrayList 如下所示:

ArrayList<Entry> test = new ArrayList<Entry>();
test.add(new Entry(20, 0));
test.add(new Entry(5, 0));
test.add(new Entry(15, 0));

现在我想要这个列表的最小值 (5) 和最大值 (20)。

我试过了:

Collections.min(test);

但它说:

绑定不匹配:集合类型的通用方法 min(Collection extends T>) 不适用于参数 (ArrayList)。推断的类型 Entry 不是有界参数 >

我也试过了:

test.length()

所以我可以做一个 for 循环。但是这种 ArrayList 也失败了。

【问题讨论】:

  • 排序。然后取第一个和最后一个元素。
  • 使用test.size() 而不是test.length()。不要犹豫,阅读docs

标签: java android arraylist


【解决方案1】:

首先,定义一个Comparator&lt;Entry&gt;,它定义了Entry的排序:

class EntryComparator implements Comparator<Entry> {
  @Override public int compare(Entry a, Entry b) {
    // ... whatever logic to compare entries.
    // Must return a negative number if a is "less than" b
    // Must return zero if a is "equal to" b
    // Must return a positive number if a is "greater than" b
  }
}

然后只需遍历列表,将每个元素与当前的最小和最大元素进行比较:

Comparator<Entry> comparator = new EntryComparator();
Iterator<Entry> it = list.iterator();
Entry min, max;
// Assumes that the list is not empty
// (in which case min and max aren't defined anyway).

// Any element in the list is an upper bound on the min
// and a lower bound on the max.
min = max = it.next();

// Go through all of the other elements...
while (it.hasNext()) {
  Entry next = it.next();
  if (comparator.compare(next, min) < 0) {
    // Next is "less than" the current min, so take it as the new min.
    min = next;
  }
  if (comparator.compare(next, max) > 0) {
    // Next is "greater than" the current max, so take it as the new max.
    max = next;
  }
}

【讨论】:

  • 创建自定义比较器并显式迭代集合并调用它有什么意义?起初,您很难尝试不弄乱所有这些 -1、0 和 1,然后……您正在从 -1,0,1 反向转换为“更小”或“更大”的关系.打电话给Collections.max(list, comparator)Collections.max(list, comparator)不是更好吗?
  • @VladimirS。 (我猜你的意思是minmax)好吧,当然可以。此解决方案 a) 更灵活,因为它适用于 IterableCollection; b) 可能更有效,因为它只迭代一次; c) 更具说明性,因为它展示了如何在不使用库方法的情况下实际实现它。 YMMV :) 你是对的,如果简洁是你的衡量标准,使用Collections 方法会“更好”。
  • 我尝试实现类 EntryComparator,但我不能将小于和大于运算符与条目结合使用。 public class EntryComparator implements Comparator&lt;Entry&gt; { @Override public int compare(Entry a, Entry b) { if(a == b){ return 0; } else if(a &lt; b){ return -1; } else if(a &gt; b){ return 1; } else{ return 0; } } }
  • @roux。您只能将原始值与&lt;&gt; 等进行比较。如果您可以这样编写比较,则不需要比较器:) 您的代码应该看起来更像if (a.getField() == b.getField()) { return 0; } ... 请添加@ 的定义987654336@这个问题,然后我可以建议一个实现。
【解决方案2】:

Entry 必须实现Comparator 接口并提供compare(T o1, T o2) 的实现。

compare 如果o1o2 相等,则返回0,如果o1 小于o2,则返回正值,否则返回负值

【讨论】:

  • 一个类自己实现Comparator是不常见的;但是,如果该类的元素有自然排序,它可能会实现Comparable
猜你喜欢
  • 2014-07-03
  • 2021-02-10
  • 2015-07-21
  • 1970-01-01
  • 1970-01-01
  • 2017-04-22
  • 2021-04-09
  • 2016-01-05
  • 2017-04-20
相关资源
最近更新 更多