Why don't Java Generics support primitive types?

后端 未结 6 845
轮回少年
轮回少年 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 07:56

    In Java, generics work the way that they do ... at least in part ... because they were added to the language a number of years after the language was designed1. The language designers were constrained in their options for generics by having to come up with a design that was backwards compatible with the existing language and the Java class library.

    Other programming languages (e.g. C++, C#, Ada) do allow primitive types to be used as parameter types for generics. But the flip side of doing this is that such languages' implementations of generics (or template types) typically entail generation of a distinct copy of the generic type for each type parameterization.


    1 - The reason generics were not included in Java 1.0 was because of time pressure. They felt that they had to get the Java language released quickly to fill the new market opportunity presented by web browsers. James Gosling has stated that he would have liked to include generics if they had had the time. What the Java language would have looked like if this had happened is anyone's guess.

提交回复
热议问题