# java泛型方法实现数值类型加法

## 1.实现数值类型加法

    public int add(int num1, int num2) {
return num1 + num2;
}

    public long add(long num1, long num2) {
return num1 + num2;
}

    public <T extends Number> double add(T t1, T t2) {
double allsum;
allsum = t1.doubleValue() + t2.doubleValue();
return allsum;
}

@Test
public void testAdd() {
int int1 = 1;
int int2 = 2;
System.out.println("Integer sum is: " + add(int1, int2));

long long1 = 100;
long long2 = 200;
System.out.println("Long sum is: " + add(long1, long2));

float f1 = 1.0f;
float f2 = 2.0f;
System.out.println("Float sum is: " + add(f1, f2));

double d1 = 1.0;
double d2 = 2.0;
System.out.println("Double sum is: " + add(d1, d2));
}

Integer sum is: 3
Long sum is: 300
Float sum is: 3.0
Double sum is: 3.0

## 2.实现数值类型集合的加法

public class GenericAdd {
//extend限制返回时候的类型
public static void sumlist(List<? extends Number> list) {
double sum = 0.0;

for(Number each : list) {
sum += each.doubleValue();
}

double sum2 = list.stream().mapToDouble(x -> x.doubleValue()).sum();
System.out.println(sum);
System.out.println(sum2);
}

//super限制添加时候的类型
public static void lowerBound(List<? super Number> list) {
Integer value1 = (Integer) list.get(0);
Float value2 = (Float) list.get(1);
System.out.println(value1 + "\t" + value2);
}

public static void main(String[] args) {
List<Number> list = new ArrayList<>();
lowerBound(list);
System.out.println("---------");

sumlist(intList);
System.out.println("---------");

sumlist(doubleList);
}

}

1   2.0
---------
6.0
6.0
---------
60.0
60.0

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120