Is there anything like Collections.max
which finds the maximal value in an array for regular arrays (such as an int[]
) in the standard Java runtime library?
No, there is no Arrays.max or a lookalike, at least in Java 6.
If you look at the signature and implementation of Collections.max, it makes quite heavy use of parameterized types. In Java, generic arrays are problematic to say the least, so maybe therefore it is not a good idea to provide a generic max implementation for arrays in Java, and keep the focus on (generic) collections.
Edit: as newacct correctly points out, the usage of generic arrays is not necessarily more problematic than the usage of generic collections, so I've edited the above text since the original was wrong. Still, the main argument of "generic arrays are problematic" is still valid in my opinion, and collections should be preferred over reference type arrays.
public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) {
if (comp==null)
return (T)max((Collection<SelfComparable>) (Collection) coll);
Iterator<? extends T> i = coll.iterator();
T candidate = i.next();
while (i.hasNext()) {
T next = i.next();
if (comp.compare(next, candidate) > 0)
candidate = next;
}
return candidate;
}