effective java 【23/24】


1、许多非受检警告很容易消除,如:
         Set<String> s = new HashSet();
        编译器提醒你  HashSet is a raw type. References to generic type HashSet<E> should be parameterized
        同时提供方法告诉你如何纠正。
        Set<String> s = new HashSet<String>();
Set<Training> hashSet1 = new HashSet<>();
Set<Training> hashSet2 = new HashSet();//unchecked assignment
Set<Training> hashSet3 = new HashSet<Training>();//explicit type arguement can be replaced with <>
2、警告:“explicit type argument xx can be replaced with <>”
     含义是:显式类型参数xx可以替换为<>
     问题就出在 
         Set<Training> hashSet3 = new HashSet<Training>();
     这种泛型只需写在Set<>里边即可。 Set里边声明了泛型以后,再在HashSet里边声明也重复冗余的。
     改成如下:
         Set<Training> hashSet3 = new HashSet<>();
     改后警告消失。
3、不能将任何元素(除了null以外)放到Collection<?>中
创建Collection类的实例时:

并尝试键入该方法add,IntelliJ可以帮助我告知add第一个参数是capture of ? e

4、原生态类型与instance of

    在参数化类型而非无限制通配符类型上使用instanceof 操作符是非法的。

public class GenericTest {

    public static void main(String[] args) {
        List<Object> o = new ArrayList<>();
//      if(o instanceof Set<?>){  //正确
//      if(o instanceof Set<Object>){  //Illegal generic type for instanceof
        if(o instanceof Set){       //正确
            Set<?> m = (Set<?>)o;
            System.out.println(m);
        }
    }
}

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值