在看Java代码的时候,老是会看见泛型中出现?比如<?> <? extends E>之类的东西,那么这到底是啥?今天看到Java程序设计进阶篇的时候才知道这是通配泛型。
先看一个小例子
public static void main(String[] args) {
GenericStack<Integer> intStack = new GenericStack<>();
intStack.push(1);
intStack.push(2);
intStack.push(-2);
System.out.println("The max number in the stack is: "+max(intStack));
}
public static double max(GenericStack<Number> stack){
double max =stack.pop().doubleValue();
while (!stack.isEmpty()){
double value = stack.pop().doubleValue();
if (value>max){
max = value;
}
}
return max;
}
这个例子定义了一个泛型max方法,返回一个栈中的最大数,在main中实例化了一个<Integer>类型的栈,放进去3个整数然后调用max方法打印结果。
然而,在调用max(intStack)这个地方,编译器报错了。因为Generic<Intege