Java erase and convert

One o'clock eye

In strict generic code, with the generic class declaration you should always take a type parameter. But in order to be consistent with the old Java code, allowing the type parameter is not specified when used with a generic class declaration. If this parameter is not specified generic class type, the parameter type is called a raw type (primitives), a first default limit is specified when the type of the parameter declaration.

When the generic object has no other information is assigned to the variable generic information, all types of information between the angle brackets have been thrown away. For example, a List <String> is converted to Type List, the List type checking into a collection element to the type of the variable upper limit (i.e. Object), this situation is erased.

Two real - Erase

class Apple<T extends Number>
{
   T size;
   public Apple()
   {
   }
   public Apple(T size)
   {
      this.size = size;
   }
   public void setSize(T size)
   {
      this.size = size;
   }
   public T getSize()
   {
      return this.size;
   }
}
public class ErasureTest
{
   public static void main(String[] args)
   {
      Apple<Integer> a = new Apple<>(6);    // ①
      // a的getSize方法返回Integer对象
      Integer as = a.getSize();
      // 把a对象赋给Apple变量,丢失尖括号里的类型信息
      Apple b = a;      // ②
      // b只知道size的类型是Number
      Number size1 = b.getSize();
      // 下面代码引起编译错误
      //Integer size2 = b.getSize();  // ③
   }
}

Three combat - erase and convert

import java.util.*;

public class ErasureTest2
{
   public static void main(String[] args)
   {
      List<Integer> li = new ArrayList<>();
      li.add(6);
      li.add(9);
      List list = li;
      // 下面代码引起“未经检查的转换”的警告,编译、运行时完全正常
      List<String> ls = list;     // ①
      // 但只要访问ls里的元素,如下面代码将引起运行时异常。
      //System.out.println(ls.get(0));
   }
}

 

Guess you like

Origin blog.csdn.net/chengqiuming/article/details/94768430