// Generics in java - java is maybe better than C++, but not by much...
// Generic types only are checked at compile time, not at runtime.
// At runtime, all generic type info is lost.
//If you create in Java:
import java.util.ArrayList;
class generalclass>
{
A x;
B y;
A[] ar;
void f() // generic code type checked
{
//int z = x+1; // won't compile (will in c++)
//y = (B)x; // will this compile? IT WILL, with a warning
// x = (A)y; // this will also compile with warning
// no generic array creation in java
//A[] array = new A[10]; // won't compile "generic array creation error"
ar = (A[])new Object[10]; // workaround, gets compiler warning.
ArrayList al = new ArrayList(); // generic "arraylist" creation OK!
}//r
// final piece of headache:
public static A z; // a static variable of generic type won't compile
}// a java generic class and it's problems.
/* Java will create internally the following class:
class generalclass
{
Object x;
Comparable y;
}
"Comparable" is a non-generic version of Comparable that contains a function
int compareTo(Comparable x)
Java will type-check your generic class at compile time, but
it is this class that's used at RUNTIME. This means that, at runtime,
there's no difference between generalclass and
generalclass: they're all the same. This is called
**Type Erasure**.
The compiler warning in y = (B)x is issued because the compiler cannot
guarantee that the cast will be valid at runtime. Normally
Object x;
Comparable y;
x = y; // will compile without errors.
y = (Comparable)x; // should compile, but may result in runtime error.
**But if x and y were instead instances of subclasses of Object and Comparable,
then the compiler will not know that the casting is invalid.
//A[] array = new A[10]; // won't compile "generic array creation error"
A[] array = (A[])new Object[10]; // workaround, gets compiler warning.
Why does it give a compiler warning? Precisely because of the example we saw
earlier:
Object[] Ar = new String[Integer]; // this is allowed, even though:
Ar[1] = 2; // this compiles but gives runtime error
The (static) type of Ar is Object[]. We don't know what the type of A
will be at runtime (from the perspective of the compiler), it could
be something incompatible with String, and this is not checked at compile
time.
So now in
A[] X = (A[]) Ar;
At compile time, we don't know what type A will be instantiated with at
compile time, so we don't know if the cast is between String[] and int[],
the compiler can't catch this.
but:
ArrayList al = new ArrayList(); // generic "arraylist" creation OK!
Because ArrayList