Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Java (but not .NET) unable to accommodate generics without the need for raw types / type erasure?

My understanding is that the reason why there are raw types and type erasure in Java is that because at the time generics was introduced, there were standard APIs that could not be made generic without breaking existing code.

Generics was also introduced to .NET at some point down the road, but this feature was implemented in a manner that does not rely on raw types or type erasure (and if it does, it does so in a manner that is transparent to the user). So existing APIs remained unchanged (for example, the code in the System.Collections namespace) and new, generic APIs were introduced (for example, the code in the System.Collections.Generic namespace).

So how come Java generics, unlike .NET generics, requires raw types / type erasure?

like image 663
J Smith Avatar asked Jul 12 '13 13:07

J Smith


2 Answers

.Net introduced generics by changing the bytecode language, virtual machine, and JITter to recognize generic types.
This was an enormous amount of work that took about two years.

Java introduced generics as a purely compile-time feature, with only small runtime changes (new metadata and reflection APIs).
This was a much simpler task, and it maintained backwards compatibility with older runtimes, but it's much more annoying to work with.

like image 149
SLaks Avatar answered Sep 16 '22 12:09

SLaks


Sun was especially keen to guarantee backward compatibility as the was a large established base of Java software. To do this they felt that the minimum of changes in the JVM was best. In hindsight, that doesn't appear to have been the best decision in the long run as it mean the JVM doesn't really understand generics and can't optimise away many redundant class checks.

Oracle by comparison have been less reluctant to change the JVM, and have suffered more serious and public bugs esp. to do with security. (They don't mean the same thing but one can lead to the other) Even so, Oracle have added just one instruction to the JVM which Java doesn't even use, whereas Sun added none so it is relative really. ;)

Microsoft on the other hand had a smaller code base for C# and customers more used to significant, even breaking changes between major versions. This means more pain in the short term but can be a better choice in the long term. You have less issues which are due to historical reason left around.

In short the difference is not technical, it is more political and historical.

like image 37
Peter Lawrey Avatar answered Sep 18 '22 12:09

Peter Lawrey