After some discussion, two changes:

- If there is only one element in the Iterable, compare it to itself to
  make sure it's not "bogus", like null in the Comparable version.
- Use our own natural ordering Comparator, as the one in Comparators is null-safe. Gah!


git-svn-id: https://samskivert.googlecode.com/svn/trunk@2773 6335cc39-0255-0410-8fd6-9bcaacd3b74c
This commit is contained in:
ray.j.greenwell
2010-04-16 00:55:13 +00:00
parent ae67d873e8
commit 0454f1cf84
@@ -111,7 +111,11 @@ public class CollectionUtil
*/ */
public static <T extends Comparable<? super T>> List<T> maxList (Iterable<? extends T> iterable) public static <T extends Comparable<? super T>> List<T> maxList (Iterable<? extends T> iterable)
{ {
return maxList(iterable, Comparators.comparable()); return maxList(iterable, new Comparator<T>() {
public int compare (T o1, T o2) {
return o1.compareTo(o2);
}
});
} }
/** /**
@@ -126,7 +130,8 @@ public class CollectionUtil
T max = itr.next(); T max = itr.next();
List<T> maxes = new ArrayList<T>(); List<T> maxes = new ArrayList<T>();
maxes.add(max); maxes.add(max);
while (itr.hasNext()) { if (itr.hasNext()) {
do {
T elem = itr.next(); T elem = itr.next();
int cmp = comp.compare(max, elem); int cmp = comp.compare(max, elem);
if (cmp <= 0) { if (cmp <= 0) {
@@ -136,6 +141,15 @@ public class CollectionUtil
} }
maxes.add(elem); maxes.add(elem);
} }
} while (itr.hasNext());
} else if (0 != comp.compare(max, max)) {
// The main point of this test is to compare the sole element to something,
// in case it turns out to be incompatible with the Comparator for some reason.
// In that case, we don't even get to this IAE, we've probably already bombed out
// with an NPE or CCE. For example, the Comparable version could be called with
// a sole element of null. (Collections.max() gets this wrong.)
throw new IllegalArgumentException();
} }
return maxes; return maxes;
} }