It is known that in Java generics are implemented on the basis of the type-erase model, that is, if there is a class

class CatContainer <T>{ T[] names; public CatContainer(){ names=(T[]) new Object[10]; } } 

Then at runtime, the program replaces the parameterized type with the type Object , that is, the program has no information about the actual type of the parameter T

Hence the question, if you create a container object as follows:

 CatContainer<String> cats=new CatContainer<>(); 

Why with this operation

 cats.names[0]=5; 

an error occurs?

Type mismatch: cannot convert from int to String

I suppose that in this case there is a preliminary (compile time) verification of the correctness of a program, during which other protection mechanisms are used, rather than when checking the correctness of a program at run time (run time). But I do not have a clear understanding of how this happens.

  • And what a mistake? Write in question - gil9red

2 answers 2

That's right, in the runtime information on generics is erased. But your question is a compilation error. The compiler is smart enough to infer the type of the array and check it with the type of object that is assigned

    Because 5 is an int type literal, which is a primitive. Primitives can automatically be boxed into the corresponding objects, in this case in Integer . But Integer does not cast on the String that you use here when declaring cats . Replace String with Integer , Number or even Object and you will compile everything, because Integer cast into any of these three.

    By the way, generics in Java are implemented not on the basis of erasing the type, but on the basis of the rules of a safe cast. Type erasure is just a side effect.