#定義泛型類#分別求Integer和Double型陣列中元素的最大值,最小值,平均值
阿新 • • 發佈:2019-01-05
public class NumFunc<T extends Number> {
T[]a;
public NumFunc(T[]a){
super();
this.a=a;
}
private void sortNums() {
// TODO Auto-generated method stub
Arrays.sort(a);
}
public T minValue(){
sortNums();
return a[0];
}
public T maxValue(){
sortNums();
return a[a.length-1];
}
public T aveValue(){
Double ave=0.0;
for(T temp:a){
ave+=temp.doubleValue();
}
ave=ave/this.a.length;
return(T)Double.valueOf(ave);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Integer[] i=new Integer[]{3 ,9,12};
Double[] d=new Double[]{1.0,1.2};
NumFunc<Integer>v=new NumFunc<Integer>(i);
System.out.println("最小值:"+v.minValue());
System.out.println("最大值:"+v.maxValue());
System.out.println("平均值:"+v.aveValue());
NumFunc<Double>vs=new NumFunc<Double>(d);
System.out .println("最小值:"+vs.minValue());
System.out.println("最大值:"+vs.maxValue());
System.out.println("平均值:"+vs.aveValue());
}
}