泛型集合有一個很大的優(yōu)點(diǎn)渊抽,就是算法只用實(shí)現(xiàn)一次仲翎。
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class GetMaxValue {
// 獲取所有實(shí)現(xiàn)了 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;
}
}