Reputation: 1
I'm trying to find the minimum and the maximum of a
ArrayList<Entry>
For example my ArrayList looks like this:
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.
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>). The inferred type Entry is not a valid substitute for the bounded parameter <T extends Object & Comparable<? super T>>
I also tried:
test.length()
so I could do a for loop. But it also failed with this kind of ArrayList.
Upvotes: 0
Views: 677
Reputation: 140318
First, define a Comparator<Entry>
which defines an ordering for 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;
}
}
Upvotes: 1
Reputation: 157437
Entry
has to implement the Comparator interface and provide an implementation for 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
Upvotes: 0