3 ms·
You can add a constraint to a generic declaration, which is an upper (or lower) bound on the allowable type arguments. e.g. class A<Y extends X> { // in
by titzer 7y ago
You can add a constraint to a generic declaration, which is an upper (or lower) bound on the allowable type arguments.
e.g.
class A<Y extends X> {
// in this scope, Y is known to be of at least type X,
// so, we can call methods on expressions of type Y
// that belong to type X (and not Object)
Y m() { ... }
}
Type arguments are omitted from usage sites. The technique is literally called erasure in papers and documentation.
a = new A<Foo>();
f = a.m(); // should return a Foo, in bytecode returns Y
// and compiler inserts a cast from Y -> Foo
Generic code is slower in Java because of these extra casts. To get back (most of) the performance, the JVM has to inline enough methods to be able to track the types from start to finish. It can't always.