Why don't Java Generics support primitive types?

后端 未结 6 840
轮回少年
轮回少年 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:51

    The collections are defined to require a type which derives from java.lang.Object. The basetypes simply don't do that.

    0 讨论(0)
  • 2020-11-21 07:53

    When creating an object, you cannot substitute a primitive type for the type parameter.As to the why of this restriction, it is a compiler implementation issue. Primitive types have their own bytecode instructions for loading and storing onto the virtual machine stack. So it is not impossible to compile primitive generics into these separate bytecode paths, but it would make the compiler complicated.

    0 讨论(0)
  • 2020-11-21 07:55

    As per Java Documentation, generic type variables can only be instantiated with reference types, not primitive types.

    This is supposed to come in Java 10 under Project Valhalla.

    In Brian Goetz paper on State of the Specialization

    There is an excellent explanation about the reason for which generic were not supported for primitive. And, how it will be implemented in future releases of Java.

    Java's current erased implementation which produces one class for all reference instantiations and no support for primitive instantiations. (This is a homogeneous translation, and the restriction that Java's generics can only range over reference types comes from the limitations of homogeneous translation with respect to the bytecode set of the JVM, which uses different bytecodes for operations on reference types vs primitive types.) However, erased generics in Java provide both behavioral parametricity (generic methods) and data parametricity (raw and wildcard instantiations of generic types.)

    ...

    a homogeneous translation strategy was chosen, where generic type variables are erased to their bounds as they are incorporated into bytecode. This means that whether a class is generic or not, it still compiles to a single class, with the same name, and whose member signatures are the same. Type safety is verified at compile time, and runtime is unfettered by the generic type system. In turn, this imposed the restriction that generics could only work over reference types, since Object is the most general type available, and it does not extend to primitive types.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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<ClassA> list = new ArrayList<ClassA>();
    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.

    0 讨论(0)
  • 2020-11-21 08:13

    In java generics are implemented by using "Type erasure" for backward compatibility. All generic types are converted to Object at runtime. for example,

    public class Container<T> {
    
        private T data;
    
        public T getData() {
            return data;
        }
    }
    

    will be seen at runtime as,

    public class Container {
    
        private Object data;
    
        public Object getData() {
            return data;
        }
    }
    

    compiler is responsible to provide proper cast to ensure type safety.

    Container<Integer> val = new Container<Integer>();
    Integer data = val.getData()
    

    will become

    Container val = new Container();
    Integer data = (Integer) val.getData()
    

    Now the question is why "Object" is chose as type at runtime?

    Answer is Object is superclass of all objects and can represent any user defined object.

    Since all primitives doesn't inherit from "Object" so we can't use it as a generic type.

    FYI : Project Valhalla is trying to address above issue.

    0 讨论(0)
提交回复
热议问题