计算数组 集合 最大值算法

package cn.gls.jdk18;

import java.util.*;

public class LargestTest {

public static void main(String[] args) {

Integer[] arr = {1,2,3,4,5,6,7};
Integer largest = max(arr);
System.out.println(largest);
List<Integer> list = new ArrayList<>();
list.add(11);
list.add(9);
list.add(7);
list.add(5);
list.add(3);
Integer max = max(list);
System.out.println(max);

}

static <T extends Comparable> T max(T[] a){
if(a.length<=0){
throw new NoSuchElementException();
}
T largest = a[0];
for(int i = 0;i<a.length;i++){
if(largest.compareTo(a[i])<0){
largest = a[i];
}
}
return largest;
}





public static <T extends Comparable> T max(Collection<T> c){
if(c.isEmpty()){
throw new NoSuchElementException();
}
Iterator<T> iter = c.iterator();
T largest = iter.next();
while (iter.hasNext()){
T next = iter.next();
if(largest.compareTo(next)<0){
largest = next;
}
}
return largest;
}




}
posted on 2019-08-10 11:52  guols  阅读(435)  评论(0编辑  收藏  举报