I am trying to create
ArrayList myList = new ArrayList();
in Java but that does not work.
Can someone explain
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:
Object, so generics is less versatile