Why don't Java Generics support primitive types?

后端 未结 6 933
轮回少年
轮回少年 2020-11-21 07:18

Why do generics in Java work with classes but not with primitive types?

For example, this works fine:

List foo = new ArrayList

        
6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-21 08:04

    Generics in Java are an entirely compile-time construct - the compiler turns all generic uses into casts to the right type. This is to maintain backwards compatibility with previous JVM runtimes.

    This:

    List list = new ArrayList();
    list.add(new ClassA());
    ClassA a = list.get(0);
    

    gets turned into (roughly):

    List list = new ArrayList();
    list.add(new ClassA());
    ClassA a = (ClassA)list.get(0);
    

    So, anything that is used as generics has to be convertable to Object (in this example get(0) returns an Object), and the primitive types aren't. So they can't be used in generics.

提交回复
热议问题