泛型集合有一个很大的优点,就是算法只用实现一次。
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class GetMaxValue {
// 获取所有实现了 Collection 接口 与 Comparable 接口对象的最大值
public static <T extends Comparable> T max(Collection<T> c) {
if (c.isEmpty()) {
throw new NoSuchElementException();
}
Iterator<T> iter = c.iterator();
T max = iter.next();
while (iter.hasNext()) {
T next = iter.next();
if (max.compareTo(next) < 0) {
max = next;
}
}
return max;
}
}