I've always wondered why generics mess this up

The java code K.I.L.E.R posted, and the one you claimed was in ArrayList (can’t find it personally) is not valid java code in the sense that it would always throw a runtime exception and fail.

“(String)new Object();” will compile, but it will always fail at runtime, just like “(String[])new Object[];” will.
And I don’t think anyone would say that “(String)new Object();” is valid java code.

[quote]The java code K.I.L.E.R posted, and the one you claimed was in ArrayList (can’t find it personally) is not valid java code in the sense that it would always throw a runtime exception and fail.
[/quote]
ArrayList is doing this in its ArrayList(int initialCapacity) constructor. But the cast there is for a generic type E (I’m assuming K.I.L.E.R was trying to do the same), which won’t produce any exception (because no cast will be made).

Anyway, such a cast is valid java code in the sense that it will compile just fine. Agreed on it being stupid and dangerous though. :wink:

So why doesn’t Sun just follow C# and implement a real version of generics?

[quote]So why doesn’t Sun just follow C# and implement a real version of generics?
[/quote]
Backward compatibility. You either have a completely new set of classes (such as Collections) for generic use, or insist that all existing code is at least recompiled.
Sun wanted existing byte code to keep working.

Can’t we have both?

[quote]Can’t we have both?
[/quote]
Of course. But we don’t. And that is something that should put a certain amount of fear in each of use w.r.t. Sun’s ongoing (in)ability not to screw-up java. But that’s been discussed at length here already.

Unfortunately this leads to frustration.
How big of an impact will .NET 2.0 have on Sun?
Will Sun be pushed further to improve Java at a faster pace?