现在的位置: 首页 > 综合 > 正文

泛型第23条:请不要在新代码中使用原生态类型

2014年02月22日 ⁄ 综合 ⁄ 共 1779字 ⁄ 字号 评论关闭
A:原生态类型如 List:不带任何类型参数的泛型名称

B:参数化类型如List<String> :表示元素类型为String的列表
C:无限制的通配符类型如List<?>:表示元素为未知类型
参数化类型优点
1)安全,提供了编译前检查
2)方便,不用显示的cast,自动完成
原生态类型存在的主要目的是兼容性。
List和List<Object>区别
后者提供了编译期检查,明确的表明集合中可以放任何类型的元素
举例:对于方法 f(List param)和方法f(List<Object>),前者可以接受List<String>和List<Integer>类型的元素,后者则不行;因为后者可以接受任何类型的元素,即是Object类的子类,而List<String>只能接受String类型的元素,List<Integer>只能接受Integer类型的元素
因此,List类型丢了了安全性,而List<Object>保证了安全性
List和List<?>区别
后者一般用于只读模式
List<?>因为不知道里面元素的类型,所以不能执行add方法,除非是null
import java.util.ArrayList;
import java.util.List;



public class ListDemo
{

     /**
      * @param args
      */
     public static void main(String[]
args) {
           // TODO Auto-generated
method stub
          List<String> strings = new ArrayList<String>();
           //方法add1和add2显示了List和List<Object>的区别
           //方法add1
           //由于参数是List,当把List<String>作为参数传进来时,list添加了一个Integer类型,
           //string列表中添加了Integer类型的元素,破坏了安全性
           add1(strings,new Integer(1));
          String s = strings.get(0); //出错,因为是Integer类型
          
           //方法add2无法通过编译,因为无法接受List<String>作为参数
           //The method add2(List<Object>, Object) in the type ListDemo
is
           //not applicable for the arguments (List<String>, Integer)
           add2(strings,new Integer(1));
          
           //方法add1和add3显示了List和List<?>的区别
           //方法add3无法通过编译,List<?>一般只能用于读取,不能add,除非是null
           //The method add(capture#1-of ?) in the type List<capture#1-of
?>
           //is not applicable for the arguments (Object)
           add3(strings,new Integer(1));
          

     }
     private static void add1(List list,Object
o)
     {
           list.add(o);
     }
     private static void add2(List<Object>
list,Object o)
     {
          list.add(o);
     }
     private static void add3(List<?>
list,Object o)
     {
          list. add(o);//错误
          list.add(null);//正确,可以添加null

     }

}

抱歉!评论已关闭.