我正在尝试找到最小值和最大值
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);
但它说:
Bound mismatch: The generic method min(Collection<? extends T>) of type Collections is not applicable for the arguments (ArrayList<Entry>). The inferred type Entry is not a valid substitute for the bounded parameter <T extends Object & Comparable<? super T>>
我也尝试过:
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/