Wednesday, 8 October 2008

Thou Shalt not Forget Those Who Are Afraid of Upgrades

I don't know how often I will have to curse about type erasure in the Java HotSpot VM. It is a pain in the… EVERYTHING. And the only reason for it is, of course, our sacred backward compatibility.
Some core library functionalities are utterly broken. How can a parameterized ArrayList's .toArray() return Object[]?
All because of type erasure. class Foo {{T[] = new T[42]; }} is illegal, because the runtime would have no clue as to what constructor to call for the array (it doesn't know its type). It boils down to: you cannot instantiate Generics. OK, you say, it wouldn't make too much of a sense anyway, but you see, it has side effects. Ever bothered to read the code of ArrayList and other parameterized standard collection types that use an array as a back end? Don't, if you want to retain your sanity. The heart of it is a lot of dirty casting, made necessary because of the way Generics are implemented (oh, the irony.)
One of the proposed features for Java 7 are Reified Generics, but somehow I doubt they'll make it into the language anytime soon. There's just still too many people around using a 1.4 VM (YES, Apple, we're looking at YOU) and introducing another substantial change to the way Generics work would make them even more complex than they already are (Yes, that PDF has more than 500 pages. Yes, it's mostly about Generics.) So, probably we'll have to just keep up with that crap. Microsoft did it right in .NET. Pity it's a closed platform.

</rant> [1] You have to first create an Array of your Type T (a literal type, not a Generic one) and then pass it to the overloaded .toArray(T[]).


David said...

Don't you ever do anything but rant?

adimit said...

Rarely. I only ever concentrate enough energy to actually go blogging when frustrated.

You're right. I should be more nice.

David said...

I didn't really want to point out anything, and I like rants. I just was interested.

ke said...

My strategy: Don't use arrays.

If you're looking for a place to be nicer on the Web, why not join the Virtual Babylon force? :-)

adimit said...

Well, tell that to the UIMA folks. Creating complex feature structures as annotation attributes can either be done in FSLists or FSArrays.

FSLists are a schoolbook example of just how stupid immutable lists will make you feel in Java.

Thanks for the link, surely some interesting reads up there ;-)