我正在尝试找到最小和最大

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);


但它说:


绑定不匹配:类型为Collections的通用方法min(Collection )不适用于参数(ArrayList )。推断的类型Entry不能有效替代有界参数>


我也尝试过:

test.length()


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

最佳答案

首先,定义一个Comparator<Entry>,它定义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;
  }
}

关于java - 如何使用Java在ArrayList <Entry>中查找最小值和最大值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33914991/

10-09 12:35