effective java 【23/24】

2022-07-25,



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);
        }
    }
}

 

 

 

 

本文地址:https://blog.csdn.net/mingyuli/article/details/112006917

《effective java 【23/24】.doc》

下载本文的Word格式文档,以方便收藏与打印。