我试图找到
的最小值和最大值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&lt;?extends T&gt;)不适用于参数(ArrayList&lt; Entry&gt;)。推断类型Entry不是有界参数的有效替代&lt; T extends Object&amp;可比&LT ;?超级T&gt;&gt;
我也尝试过:
test.length()
所以我可以做一个for循环。但它也失败了这种ArrayList。
答案 0 :(得分:1)
首先,定义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;
}
}
答案 1 :(得分:0)