System.out.println(getMax_Min(in)); //数组中最大值为:17, 最小值为:1
System.out.println(getMax_Min(d)); // 数组中最大值为:328.0, 最小值为:123.323
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public static String getMax_Min(Object arr){
Class clazz = arr.getClass();
List list = new ArrayList();
int length = 0;
if (clazz.isArray()) { // 判断是不是数组
length = Array.getLength(arr);
Class componentType = clazz.getComponentType(); // 获得数组的类型
if (componentType == int.class
|| componentType == double.class
|| componentType == float.class
|| componentType == long.class) {
for (int i = 0; i < length; i++) {
// 如果是基本类型的数字数组,需要手动添加到集合
list.add(Array.get(arr, i));
}
} else if (componentType == Integer.class
|| componentType == Float.class
|| componentType == Double.class
||componentType == Long.class) {
// 如果是包装类型,用Arrays的asList()方法
Object[] newArr = (Object[]) Array.newInstance(componentType,
length);
System.arraycopy(arr, 0, newArr, 0, length);
list = Arrays.asList(newArr);
} else {
throw new RuntimeException("请出入数字数组");
}
} else {
throw new RuntimeException("请输入数组");
}
return "数组中最大值为:"+Collections.max(list)+", 最小值为:"+Collections.min(list);
}
}
/*
思路:
* 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, 最小值为:32.4
System.out.println(getMax_Min(in)); //数组中最大值为:17, 最小值为:1
System.out.println(getMax_Min(d)); // 数组中最大值为:328.0, 最小值为:123.323
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public static String getMax_Min(Object arr){
Class clazz = arr.getClass();
List list = new ArrayList();
int length = 0;
if (clazz.isArray()) { // 判断是不是数组
length = Array.getLength(arr);
Class componentType = clazz.getComponentType(); // 获得数组的类型
if (componentType == int.class
|| componentType == double.class
|| componentType == fl