Java泛型的理解

泛型的erasure

public class Widgets<T> {
    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.
    }

數(shù)組是協(xié)變的

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) {
        // 創(chuàng)建一個Apple[]數(shù)組, 并將它賦給一個Fruit[]數(shù)組.
        Fruit[] fruit = new Apple[10];

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

        /**
         * 1. 編譯器允許將一個Fruit對象放置到Fruit[]數(shù)組中,這是行的通的,因?yàn)閒ruit被聲明為一個Fruit[]的引用; 
         * 2. 在運(yùn)行時拋java.lang.ArrayStoreException異常,因?yàn)閒ruit引用真正指向的是Apple[]的對象.
         */
        try {
            fruit[2] = new Fruit();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        try {
            fruit[3] = new Orange();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 做CS61B的homework6,碰到了一個問題,本來想忽視,問了之后才發(fā)現(xiàn)是大問題。前提:我現(xiàn)在要構(gòu)造一個siz...
    Richardo92閱讀 506評論 0 1
  • 泛型是Java SE1.5的新特性,泛型的本質(zhì)是參數(shù)化類型,也就是說所操作的數(shù)據(jù)類型被指定為一個參數(shù)。這種參數(shù)類型...
    流氓劍客閱讀 275評論 0 0
  • 關(guān)于java泛型的理解,泛型是java5.0增加的一種新的機(jī)制,與c++的模板很相似但卻有很多的不同,當(dāng)...
    一個壞人_9c31閱讀 263評論 0 0
  • http://www.itdecent.cn/p/7e3e2b898143這是上次寫的泛型,當(dāng)時其實(shí)還是一知半解。...
    Richardo92閱讀 420評論 0 1
  • 泛型是Java 1.5引入的新特性。泛型的本質(zhì)是參數(shù)化類型,這種參數(shù)類型可以用在類、變量、接口和方法的創(chuàng)建中,分別...
    何時不晚閱讀 3,122評論 0 2

友情鏈接更多精彩內(nèi)容