Fork me on GitHub

通配符

泛型技术解决了向下转型的安全性问题,随之而来,又会产生一个新的问题:如果泛型类设置的不同,方法里面的参数引用也必定是不同的,为了解决这个问题,引入了通配符的使用

如果没有通配符,在泛型方法里面定义多个泛型类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Message<T>{
private T msg;
public void setMsg(msg) {
this.msg=msg;
}
public T getMsg() {
return this.msg;
}
}
public class testDemo7{
public static void main(String args[]) {
Message<String> m=new Message<>();
m.set("Hello");
Message<Integer> n=new Message<>();
n.set(19);
fu(m);
fun(n);
}
public static void fun(Message<String> m) {
System.out.println(m.getMsg());
ystem.out.println(n.getMsg());
}
}

这样程序显然会报错

可以使用通配符”?”解决参数的传递问题,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

class Message<T>{
private T msg;
public void setMsg(T msg) {
this.msg=msg;
}
public T getMsg() {
return this.msg;
}
}
public class testDemo7{
public static void main(String args[]) {
Message<String> m=new Message<>();
m.setMsg("Hello");
Message<Integer> n=new Message<>();
n.setMsg(19);
fun(m);
fun(n);
}
public static void fun(Message<?> m) {
System.out.println(m.getMsg());
}
}

使用通配符”?”,不管何种泛型类型,fun方法对抗与接收参数

在”?”通配符的基础上还有两个子通配符:

  • “? extends 类”,eg:? extends Number: 意味着可以设置Number或者Number的子类

  • “? super 类”,eg:? super String: 只能设置String和他的父类Object

-------------本文结束感谢您的阅读-------------
Donate comment here