I am trying to create
ArrayList myList = new ArrayList();
in Java but that does not work.
Can someone explain
For your question, Java objects are somewhat equivalent to pointers in C++.
Java does garbage collection because those dynamic obejcts will be "unseen" (stop being pointed) at some point and then a space cleaning is needed.
int
is recognized as a primitive type so that makes impossible to return null
and that's the reason why Java generics cannot accept primitve types. To indicate that an element isn't stored inside a Java container as Map
, Set
, List
, a method will return null
. Then what are you going to return if you can't return null
?
For std::array
, static and dynamic arrays, C++ forces you to define a default constructor, it's because as C++ arrays are arrays of types instead of arrays of pointers as in Java. You have to indicate which default value (null
value in Java) is going to take the objects in such structure.
Think about it, in Java any object in an array is null
by default, in C++ it isn't unleast you declare an array of pointers and set all those at 0x0
or (preferable) as nullptr
.
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.