[英]How to find the minimum and maximum in a ArrayList<Entry> using Java
I'm trying to find the minimum and the maximum of a 我正在尝试找到最小和最大
ArrayList<Entry>
For example my ArrayList looks like this: 例如,我的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));
now I want the minimum(5) and the maximum(20) of this list. 现在我想要这个列表的最小值(5)和最大值(20)。
I tried it with: 我尝试了:
Collections.min(test);
But it says: 但它说:
Bound mismatch: The generic method min(Collection<? extends T>) of type Collections is not applicable for the arguments (ArrayList<Entry>). 绑定不匹配:类型为Collections的通用方法min(Collection <?扩展T>)不适用于参数(ArrayList <Entry>)。 The inferred type Entry is not a valid substitute for the bounded parameter <T extends Object & Comparable<? 推断的类型Entry不能有效替代有界参数<Textended Object&Comparable <? super T>> 超级T >>
I also tried: 我也尝试过:
test.length()
so I could do a for loop. 所以我可以做一个for循环。 But it also failed with this kind of ArrayList. 但是,这种ArrayList也失败了。
First, define a Comparator<Entry>
which defines an ordering for Entry
: 首先,定义一个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
}
}
Then just iterate through the list, comparing each element to the current minimum and maximum elements: 然后只需遍历列表,将每个元素与当前的最小和最大元素进行比较:
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;
}
}
Entry
has to implement the Comparator interface and provide an implementation for compare(T o1, T o2)
. Entry
必须实现Comparator接口,并提供compare(T o1, T o2)
。
compare
returns 0
if o1
and o2
are equals, a positive value if o1 is less then o2, a negative value otherwise 如果o1
和o2
相等,则compare
返回0
如果o1
小于o2,则compare
返回正值;否则,返回负值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.