How are Java generics different from C++ templates

2020-02-07 16:14发布

I am trying to create

ArrayList<int> myList = new ArrayList<int>();

in Java but that does not work.

Can someone explain why int as type parameter does not work?
Using Integer class for int primitive works, but can someone explain why int is not accepted?

Java version 1.6

7条回答
冷血范
2楼-- · 2020-02-07 17:09

Java generics are so different from C++ templates that I am not going to try to list the differences here. (See What are the differences between “generic” types in C++ and Java? for more details.)

In this particular case, the problem is that you cannot use primitives as generic type parameters (see JLS §4.5.1: "Type arguments may be either reference types or wildcards.").

However, due to autoboxing, you can do things like:

List<Integer> ints = new ArrayList<Integer>();
ints.add(3); // 3 is autoboxed into Integer.valueOf(3)

So that removes some of the pain. It definitely hurts runtime efficiency, though.

查看更多
登录 后发表回答