A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© David19910809 中级黑马   /  2015-6-4 22:48  /  207 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 David19910809 于 2015-6-4 22:57 编辑

     
  • 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()) ;       // 取得信息
  •     }
  • };

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马