user2779311 user2779311 - 1 year ago 87
Java Question

Working of generics in Java

I am trying to see the working of Generics and it says that classes are compiled to normal classes and there is no type mentioned anywhere and there is checkcast operator which is passed the type to which the Object class is cast to which we are getting from ArrayList.

String i=ArrayListObject.get(position);

But when there are no types how come the compiler know that a generic ArrayList can only store the type declared in <>. Where is this information stored while compiling the class.
kindly update

Answer Source

This is only half of the truth.

Yes, at runtime, none of that type information is used; just "Objects" are moved around. That is what is called type erasure.

But: the information which fields, methods, ... were defined using some generic T is very well compiled into the class file. So that a compiler can read that class file; and can understand that you want to instantiate some ArrayList<String> for example.

In other words: you are talking about two different things here: A) a compiler reading the class file so it can do its job and B) a JVM reading class files to run code.

So, when you are really curious where exactly that information is stored, see here!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download