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
Generics are generic until the types are substituted for them at runtime. Templates are specialized at compile time so they are not still parameterized types at runtime. The common language runtime specifically supports generics in MSIL.
A C++ template gets reproduced and re-compiled entirely whenever a template is instantiated with a new class. The main difference is that Java generics are encapsulated. The errors are flagged when they occur and not later when the corresponding classes are used/instantiated.
While, C++ is platform dependent language, Java is platform independent language. The above statement is the reason why C++ is able to provide true generic types. While Java does have strict checking and hence they don't allow using generics the way C++ allows it.
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.
The reason that int
doesn't work, is that you cannot use primitive types as generic parameters in Java.
As to your actual question, how C++ templates are different from Java generics, the answer is that they're really, really different. The languages essentially apply completely different approaches to implementing a similar end effect.
Java tends to focus on the definition of the generic. That is, the validity of the generic definition is checked by only considering the code in the generic. If parameters are not properly constrained, certain actions cannot be performed on them. The actual type it's eventually invoked with, is not considered.
C++ is the opposite. Only minimal verification is done on the template itself. It really only needs to be parsable to be considered valid. The actual correctness of the definition is done at the place in which the template is used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With