关于任意数字类型的数组求最大值解决办法 (一)

2014-11-24 11:01:08 · 作者: · 浏览: 3

有两种思路:

一种是重载方式(就是有几种数字数组就写几个重载方法,因为Arrays中的toString()方法就是这么干的(黄玉昆给的解释,很好),毕竟基本数据类型没封装类好操作)。


[java]
public class GetMaxAndMin {

public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = new int[]{1,21,2,24,4,64,6,86,8,98,9};
String max_min = getMax_Min(arr);
System.out.println(max_min); //打印结果:数组中,最大值为:98 , 最小值为 :1

}
public static String getMax_Min(int[] arr){
int max = arr[0];
int min = arr[0];
for(int x = 1;x if(max max = arr[x];
if(min>arr[x])
min = arr[x];
}
return "数组中,最大值为:"+max+" , 最小值为 :"+min;
}
public static String getMax_Min(double[] arr){
double max = arr[0];
double min = arr[0];
for(int x = 1;x if(max max = arr[x];
if(min>arr[x])
min = arr[x];
}
return "数组中,最大值为:"+max+" , 最小值为 :"+min;
}
public static String getMax_Min(long[] arr){

long max = arr[0];
long min = arr[0];
for(int x = 1;x if(max max = arr[x];
if(min>arr[x])
min = arr[x];
}
return "数组中,最大值为:"+max+" , 最小值为 :"+min;
}

}

public class GetMaxAndMin {

public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = new int[]{1,21,2,24,4,64,6,86,8,98,9};
String max_min = getMax_Min(arr);
System.out.println(max_min); //打印结果:数组中,最大值为:98 , 最小值为 :1

}
public static String getMax_Min(int[] arr){
int max = arr[0];
int min = arr[0];
for(int x = 1;x if(max max = arr[x];
if(min>arr[x])
min = arr[x];
}
return "数组中,最大值为:"+max+" , 最小值为 :"+min;
}
public static String getMax_Min(double[] arr){
double max = arr[0];
double min = arr[0];
for(int x = 1;x if(max max = arr[x];
if(min>arr[x])
min = arr[x];
}
return "数组中,最大值为:"+max+" , 最小值为 :"+min;
}
public static String getMax_Min(long[] arr){

long max = arr[0];
long min = arr[0];
for(int x = 1;x if(max max = arr[x];
if(min>arr[x])
min = arr[x];
}
return "数组中,最大值为:"+max+" , 最小值为 :"+min;
}

}


另一种是利用反射(开始我想的也是这种,可是没有想到结合集合去解决在数组类型未知时怎么比较大小,问了下老师得到了满意的答复)
不能像这样用泛型getMax(T[]),因为T[]不接收基本类型的数组。
代码如下:

//这是关键:因为不确定数组的数据类型,无法用>比较大小,可以考虑是用集合工具了Collections的max()方法

[java]
/*
思路:
* 1、传入一个数组引用获取其字节码文件
* 2、用Class的静态方法,isArray判断是不是数组
* 3、是数组的话通过componentType()方法获取其数组类型
* 4、对类型进行判断,是基本数据类型就一个个添加进list集合(自动装箱)
* 5、不是的话就用Object中的arrayCopy(),直接添加进list集合。
* 6、因为jvm不知道数组类型,所以不能用<、>比较符号,用Collections中的max,min方法获取集合中的最大值最小值
* */


class GetMaxAndMin{
public static void main(String[] args){

int[] ins = {1,21,2,24,4,64,6,86,8,98,9};
double[] ds = { 123.323, 123.54, 328.0 };
float[] fs = { 123.5f, 32.4f };
Integer[] in = { 1, 2, 3, 4, 17 };
Double[] d = { 123.323, 123.54, 328.0 };
System.out.println(getMax_Min(ins)); //数组中最大值为:98, 最小值为:1
System.out.println(getMax_Min(ds)); // 数组中最大值为:328.0, 最小值为:123.323
System.out.println(getMax_Min(fs)); //数组中最大值为:123.5, 最