java5-泛型通配符

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37625860/article/details/78891904

如果有两个类:

Shape类

public class Shape{
     //价钱
     private String area;
}

Square类
public class Square extends Shape{
     //价钱
     private String area;
}

 
 

我们要写一个计算总价的方法,要求可以传shape集合或Square集合。

那么,java5之前,只能通过数组的方式传入参数并计算

例:

public static double totalArea(Shape[] arr){
    //总价   
    double total =0;

    for(Shape s:arr){
       if(s!=null)
          total+=s.area();
    }
     return total;
}
在java5之后,引入了泛型,那么我们可以通过Collection来实现此算法吗?

如:

public static double totalArea(Collection<Shape> arr){
	double total = 0;
	
	for(Shape s:arr){
		if(s!=null)
			total+=s.getArea();
	}
	
	return total;
}
大家可以试试!!!

----------拦截线----------------



结果是,不可以!!!会抛出一个ArrayStoreException异常。

因为泛型集合不是协变的。

所以,java5后引入了通配符  ?,通配符用来表示参数类型的子类或超类

public static double totalArea(Collection<? extends Shape> arr){
	double total = 0;
	
	for(Shape s:arr){
		if(s!=null)
			total+=s.getArea();
	}
	
	return total;
}

当然,也可以不加限制条件(extends Shapre),默认extends Object。

到此,通配符的作用已经结束,快去尝试把!!!


猜你喜欢

转载自blog.csdn.net/m0_37625860/article/details/78891904