Java 泛型详解

来源:互联网 发布:cdo 首席数据官 编辑:程序博客网 时间:2024/06/06 14:21

普通泛型

public class Point<T> {    private T var ;      public T getVar()    {        return var ;      }      public void setVar(T var)    {        this.var = var ;      }    public String toString()    {        return this.var.toString() ;      }}public class NotePad<K, V> {    private K key ;     private V value ;    public K getKey()    {          return this.key ;      }      public V getValue()    {          return this.value ;      }      public void setKey(K key)    {          this.key = key ;      }      public void setValue(V value)    {          this.value = value ;      } }public class Test1{    public static void main(String[] args)     {        Point<String> point = new Point<String>();        point.setVar("test");        System.out.println(point.getVar());                Point<Integer> point2 = new Point<Integer>();        point2.setVar(1);        System.out.println(point2.getVar());                NotePad<Integer, String> notePad = new NotePad<Integer, String>();        notePad.setKey(1);        notePad.setValue("value");        System.out.println(notePad.getKey());        System.out.println(notePad.getValue());    }}

通配符

public class Test2 {/** * 可以接收任意的泛型对象   * @param temp */public static void fun(Point<?> temp){        System.out.println("内容:" + temp) ;      }public static void main(String[] args) {Point<String> point = new Point<String>();point.setVar("it") ;        fun(point) ;}}


原创粉丝点击