2

我已经阅读了很多关于 java 中的通用概念的内容。我已经有了一些疑问,这些疑问在StackOverflow上得到了准确的答案。

我不认为这个问题在这里之前被问过。
我搜索了很多。但是,我在任何地方都找不到这个问题的答案,


在(a)编译时
(b)运行时执行时 ,通用程序(在java中)中发生了什么以及如何发生。

就像....
一步一步会发生什么?
编译器在哪里存储通用信息等...

任何人都可以用示例代码解释我吗?

谢谢。

编辑:我知道一些概念,例如删除所有通用信息的类型擦除,但我不知道通用程序的所有步骤。

4

2 回答 2

4

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.

于 2011-04-19T03:52:55.937 回答
0

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.

于 2011-04-19T03:51:32.323 回答