JAVA_はジェネリック配列を作成できません



Java_ Cant Create Generic Array



どの文法規則にも意図があり、JAVAはジェネリック配列を作成できず、例外もありません。

コードの一部で理由を確認できます

import java.util.ArrayList public class demo { public static void main(String[] args){ Object o = new ArrayList[1]//Assuming you can create a generic array like this, because of the polymorphism, the array of subclasses can be instantiated to the parent class, so we can use ArrayList[1] for Object The type of variable o opens up space. o[0] = new ArrayList()// At this point, we use polymorphism to instantiate ArrayList to o. There is obviously an error here. The o type is actually an ArrayList type, but we instantiate it with ArrayList. } }

まず、ジェネリック型とその元のクラスの間の継承関係には、 共分散 つまり、元のクラス間の継承関係は、ジェネリック化されたクラスに渡されません。たとえば、元のクラスの息子は父親のサブクラスですが、息子と父親の間に継承関係はありません。