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

后端 未结 8 1382
眼角桃花
眼角桃花 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:44

    You can't use primitives as type parameters in Java. Java's generics worth through type erasure, meaning that the compiler checks that you're using the types as you've defined them, but upon compilation, everything is treated as an Object. Since int and other primitives aren't Objects, they can't be used. Instead, use Integer.

提交回复
热议问题