Fork me on GitHub

通配符

-----------siwuxie095

   

   

   

   

   

通配符 ? 的使用:

   

代码:

   

package com.siwuxie095.generic;

   

class Info<T>{

private T key;

   

public T getKey() {

return key;

}

   

public void setKey(T key) {

this.key = key;

}

 

//为了方便能具体的得到key的值,复写 toString() 方法

@Override

public String toString() {

return this.getKey().toString();

}

}

   

public class GenericDemo04 {

   

public static void main(String[] args) {

Info<String> i=new Info<String>();

i.setKey("siwuxie095");

tell(i);

}

 

//传入 Info 类型的参数,因为 Info指定了泛型

//在主方法中使用时也不知道要传入什么类型的实参

//为了能接收所有数据类型,可以写 Object 类型

// public static void tell(Info<Object> i) {

// System.out.println(i);

// }

 

 

//但如果写Object,主方法中调用 tell() 时会类型不匹配

//除非把tell()方法中Object换成 String,或 把主方法中的String换成Object

//前者限制了 tell() 不合适,后者类型过于宽泛

//所以要用通配符:? 无论什么类型都可以使用

public static void tell(Info<?> i) {

System.out.println(i);

}

   

}

   

   

运行一览:

   

   

   

   

   

【made by siwuxie095】

posted on 2017-03-18 23:13  siwuxie095  阅读(103)  评论(0编辑  收藏  举报

导航