Wikipedia says for Generics - "One version of a class or function compiled, works for all type parameters."

How does Java do this? If multiple classes are not created, how does it support multiple typed instances of the Generic class? Until now, I believed this to be similar to C ++, but now I'm completely confused. Can't figure out how Java disables this?

-Ajay

+3
source share
3 answers

Since only reference types can be used as general type arguments in Java, and all pointers are the same size, you can use the same byte code.

, Java / . . T ( Object, ). ,

class Complex<N extends Number> {
    N real;
    N imag;
}

class Complex {
    Number real;
    Number imag;
}

.

, . ,

new N();

, N, , , . ,

(N) n

, Java . , . . ( ), . ,

boolean right(Complex<Integer> c) {
    return c.real > 0;
}

boolean right(Complex c) {
    return ((Integer) c.real) > 0;
}

, Java , .NET. , ...

+4

. Java - . Object s .


Michael :

. , , .

:

, java.util.List, , . , . , , , . :

, , , . , .

+6

good question. Genetic information is not stored during operation. For example, if you have this code

List<Apple> apples = new ArrayList<Apple>();    // this is a list of apples

But at runtime, it becomes:

List apples = new ArrayList();    // this is how it looks in runtime
0
source

All Articles