Java泛型的理解

泛型的erasure

public class Widgets {
    private final int SIZE = 100;

    public void f(Object arg) {
        /**
         * Compile error:
         * Cannot perform instanceof check against type parameter T. 
         * Use its erasure Object instead since further generic
         * type information will be erased at runtime.
         */
        if (arg instanceof T) { //Error
        }
        
        /**
         * Compile error:
         * Cannot instantiate the type T.
         * Partly because of erasure, and partly the compiler cannot verify that
         * T has a default (no-arg) constructor
         */
        T var = new T(); // Error
        
        /**
         * Compile error:
         * Cannot create a generic array of T.
         */
        T[] array1 = new T[SIZE]; // Error
        
        /**
         * Compile warning:
         * Type safety: Unchecked cast from Object[] to T[].
         */
        T[] array2 = (T[]) new Object[SIZE]; //warning.
    }

数组是协变的

package com.yxf.hellojava;

class Fruit {
}

class Apple extends Fruit {
}

class Jonathan extends Apple {
}

class Orange extends Fruit {
}

public class CovariantArrays {

    public static void main(String[] args) {
        // 创建一个Apple[]数组, 并将它赋给一个Fruit[]数组.
        Fruit[] fruit = new Apple[10];

        fruit[0] = new Apple();
        fruit[1] = new Jonathan();

        /**
         * 1. 编译器允许将一个Fruit对象放置到Fruit[]数组中,这是行的通的,因为fruit被声明为一个Fruit[]的引用; 
         * 2. 在运行时抛java.lang.ArrayStoreException异常,因为fruit引用真正指向的是Apple[]的对象.
         */
        try {
            fruit[2] = new Fruit();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        try {
            fruit[3] = new Orange();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(Java泛型的理解)