How are Java generics different from C++ templates? Why can't I use int as a parameter?

后端 未结 8 1372
眼角桃花
眼角桃花 2020-12-12 19:02

I am trying to create

ArrayList myList = new ArrayList();

in Java but that does not work.

Can someone explain

8条回答
  •  旧巷少年郎
    2020-12-12 19:41

    The main difference is in way they are implemented, but their names accurately describe their implementation.

    Templates behave like templates. So, if you write:

    template
    void f(T s)
    {
        std::cout << s << '\n';
    }
    
    ...
    int x = 0;
    f(x);
    ...
    

    Compiler applies the template, so in the end compiler treats the code like:

    void f_generated_with_int(int s)
    {
        std::cout << s << '\n';
    }
    
    ...
    int x = 0;
    f_generated_with_int(x);
    ...
    

    So, for each type which is used to call f a new code is "generated".

    On the other hand, generics is only typechecked, but then all type information is erased. So, if you write:

    class X {
        private T x;
    
        public T getX() { return x; }
        public void setX(T x) { this.x = x; }
    }
    
    ...
    Foo foo = new Foo();
    X x = new X<>();
    x.setX(foo);
    foo = x.getX();
    ...
    

    Java compiles it like:

    class X {
        private Object x;
    
        public Object getX() { return x; }
        public void setX(Object x) { this.x = x; }
    }
    
    ...
    Foo foo = new Foo();
    X x = new X();
    x.setX(foo);
    foo = (Foo)x.getX();
    ...
    

    In the end:

    • templates require instantiation of each call to templated function (in compilation of each .cpp file), so templates are slower to compile
    • with generics you can't use primitives, because they are not Object, so generics is less versatile

提交回复
热议问题