I have read much about the generic concept in java. I already had some doubt, which were cleared with precise answers on StackOverflow.
I don't think this question has been asked before here.
I searched a lot. But, nowhere I found answer to my this question,What and how all things happen in a generic program (in java) at
(a) Compile time (b) Runtime execution.Like ....
What happens step wise ? Where the compiler stores the generic information etc ...
Can anyone explain me with a sample code ?
Thanks.
EDIT : I know some concept like type erasure removing all the generic information but I am unaware of all the s开发者_开发百科teps for a generic program.
Read the Angelika Langer FAQ About Generics you will most likely find answers to all your questions there.
The book The Java Programming Language 4th Edition contains a good chapter on the subject.
And of course there is no better reference than the Java Language Specification which you can get for free.
The book Java Generics and Collections is also a very good book on the subject if you really intend to go that deep. I found a PDF version of the book here. Unfortunately it only contains a few pages.
If you use .Net and Java, then http://jorudolph.wordpress.com/2010/04/21/net-generics-implementation/ provides a compare & contrast view.
http://www.codeproject.com/KB/java/GenericsInJavaPartII.aspx is an explanation with sample code showing the implementation's implications.
Briefly stated....
Part A:
The compiler wipes out ("erases") the generic bits (so ArrayList turns into ArrayList). Then, when an object is pulled out of the collection (say, al.get(0)), the compiler inserts the code that converts the data type (aka "boxing") (turning al.get(0) into (StackExchange)al.get(0)).
Part B:
There is no Part B. :)
Part Z:
Generics in Java were implemented about a decade after the language was first released. Consequently, possibly in the name of backwards compatibility, generics in Java only act as syntactic sugar. Syntactic sugar is a fancy way to say "You could write this code yourself but the compiler lets you type in a shortcut instead." For example, before generics showed up in Java, you could already write (StackExchange)al.get(0). The compiler merely inserts the code for you if you use generics.
精彩评论