Java's type wildcard combat

One o'clock eye

  • List <String> object can not be treated as List <Object> object uses, that is to say: a subclass of List <String> class is not a List <Object> class.

  • Generic arrays and different: Foo is assumed that a sub-type (subclass or sub-interface) Bar, then Foo [] is still Bar [] subtype; but G <Foo> not G <Bar> subtype .  

  • In order to represent various generic List parent, we need to use a wildcard type, type the wildcard is a question mark, the argument passed to a question mark as a List collection type, writing (?): List (meaning unknown element type <?> the List). The question mark (?) Is known as a wildcard, it can match any type of element types.

Two generic good design

Code 1

import java.util.*;

public class ArrayErr
{
   public static void main(String[] args)
   {
      // 定义一个Integer数组
      Integer[] ia = new Integer[5];
      // 可以把一个Integer[]数组赋给Number[]变量
      Number[] na = ia;     // A 处
      // 下面代码编译正常,但运行时会引发ArrayStoreException异常
      // 因为0.5并不是Integer
      na[0] = 0.5;   // B 处
      List<Integer> iList = new ArrayList<>();
      // 下面代码导致编译错误
      //List<Number> nList = iList; // C 处
   }
}

2 runs

Exception in thread "main" java.lang.ArrayStoreException: java.lang.Double
    at ArrayErr.main(ArrayErr.java:23)

3 Description

A code is not at compile-time error, but will cause a runtime error at B.

B is a compile-time error code directly.

This is the difference between arrays and generics, generic design due to the array of early detection of errors and not only to run discovery.

Three combat - type of use wildcards

Code 1

import java.util.*;

public class ArrayErr
{
   public static void main(String[] args)
   {
      List<String> c = new ArrayList<String>();
      c.add("第一个");
      c.add("第二个");
      test(c);

      // 下面这种用法是错误的,这种类型通配不能加元素
      List<?> wrongList = new ArrayList<String>();
      //wrongList.add(new Object());
   }

   // 这种问号类型通配符表示各种泛型的父类,它的元素类型可以匹配任意类型,可以用到遍历中
   public static void test(List<?> c)
   {
      for(int i=0;i<c.size();i++)
      {
         System.out.println(c.get(i));
      }
   }
}

2 runs

第一个
第二个

3 Description

Wildcards can be used to traverse the type of scene, not to add a scene.

Guess you like

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