0

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

user2779311
  • 1,688
  • 4
  • 23
  • 31
  • 2
    It's called type erasure. https://docs.oracle.com/javase/tutorial/java/generics/erasure.html. Java generics are not done like C++ generics, where an entirely unique class is created for each type. – duffymo Sep 19 '16 at 15:50
  • @duffymo He knows about type erasure. He asks how the compiler can do its job when all type information is erased. – GhostCat Sep 19 '16 at 15:57

1 Answers1

3

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!

Community
  • 1
  • 1
GhostCat
  • 137,827
  • 25
  • 176
  • 248