java 泛型

来源:互联网 发布:销售出入库软件 编辑:程序博客网 时间:2024/05/29 19:21

一、普通泛型

class Point< T>{  // 此处可以随便写标识符号,T是type的简称   private T var ; // var的类型由T指定,即:由外部指定   public T getVar(){ // 返回值的类型由外部决定    return var ;   }   public void setVar(T var){ // 设置的类型也由外部决定    this.var = var ;   }  };  public class GenericsDemo06{   public static void main(String args[]){    Point< String> p = new Point< String>() ; // 里面的var类型为String类型    p.setVar("it") ;  // 设置字符串    System.out.println(p.getVar().length()) ; // 取得字符串的长度   }  }; 


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 GenericsDemo09{   public static void main(String args[]){    Notepad< String,Integer> t = null ;  // 定义两个泛型类型的对象    t = new Notepad< String,Integer>() ;  // 里面的key为String,value为Integer    t.setKey("汤姆") ;  // 设置第一个内容    t.setValue(20) ;   // 设置第二个内容    System.out.print("姓名;" + t.getKey()) ;  // 取得信息    System.out.print(",年龄;" + t.getValue()) ;  // 取得信息    }  };

二、通配符

class Info< T>{   private T var ;  // 定义泛型变量   public void setVar(T var){    this.var = var ;   }   public T getVar(){    return this.var ;   }   public String toString(){ // 直接打印    return this.var.toString() ;   }  };  public class GenericsDemo14{   public static void main(String args[]){    Info< String> i = new Info< String>() ;  // 使用String为泛型类型    i.setVar("it") ;       // 设置内容    fun(i) ;   }   public static void fun(Info< ?> temp){  // 可以接收任意的泛型对象    System.out.println("内容:" + temp) ;   }  };  

三、受限泛型

class Info< T>{   private T var ;  // 定义泛型变量   public void setVar(T var){    this.var = var ;   }   public T getVar(){    return this.var ;   }   public String toString(){ // 直接打印    return this.var.toString() ;   }  };  public class GenericsDemo17{   public static void main(String args[]){    Info< Integer> i1 = new Info< Integer>() ;  // 声明Integer的泛型对象    Info< Float> i2 = new Info< Float>() ;   // 声明Float的泛型对象    i1.setVar(30) ;         // 设置整数,自动装箱    i2.setVar(30.1f) ;        // 设置小数,自动装箱    fun(i1) ;    fun(i2) ;   }   public static void fun(Info< ? extends Number> temp){ // 只能接收Number及其Number的子类    System.out.print(temp + "、") ;   }  }; 




原创粉丝点击