package cn.zzx.than;
/**
* 泛型类
*
*
* @param
*/
public class Than {
private T max; // 最大值
private T min; // 最小值
/**
* max的属性
*
* @return
*/
public T getMax() {
return max;
}
public void setMax(T max) {
this.max = max;
}
/**
* min的属性
*
* @return
*/
public T getMin() {
return min;
}
public void setMin(T min) {
this.min = min;
}
/**
* 构造方法并重载
*/
public Than() {
super();
}
public Than(T max, T min) {
super();
this.max = max;
this.min = min;
}
/**
* 调用toString方法
*/
public String toString() {
return "Than [max=" + max + ", min=" + min + "]";
}
}
package cn.zzx.than;
public class Calc {
/**
* 泛型方法
*在泛型 extends是实现接口也可以是继承,extends Comparable在这里是指接口
*泛型中,extends并不代表继承,它是类型范围限制
*/
public static Than maxmin(T nums[]) {
T mMax = nums[0]; //初始值
T mMin = nums[0]; //初始值
for (int i = 1; i < nums.length; i++) {
if (mMax.compareTo(nums[i]) < 0) { //mMax大于nums[i]
mMax = nums[i];
}
if (mMin.compareTo(nums[i]) > 0) { //mMin小于nums[i]
mMin = nums[i];
}
}
return new Than(mMax, mMin); //返回初始值
}
}
package cn.zzx.than;
/**
*
* 泛型要用包装(封装)类型
*
*/
public class Test {
public static void main(String[] args) {
Integer[] a = { 22, 33, 45, 11, 12, 10 };
Than result = Calc.maxmin(a);
System.out.println("最大值:" + result.getMax() + "\t最小值:" + result.getMin());
String[] b = {"aa","bb","dd","AA","BB","DD","a","b"};
Than result2 = Calc.maxmin(b);
System.out.println("最大值:" + result2.getMax().toString() + "\t最小值:" + result2.getMin().toString());
System.out.println(result2);
}
}