Why don't Java Generics support primitive types?

后端 未结 6 911
轮回少年
轮回少年 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: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 {
    
        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 val = new Container();
    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.

提交回复
热议问题