[Java] Tim Bray on Java Generics, Arrays, and Comparables

http://www.tbray.org/ongoing/When/200x/2005/06/12/Comparable

Tim Bray bangs his head against the wall when using Java generics. I just turned off the compiler warnings in Eclipse. I don't care how powerful generics are, the syntax is ugly and the effects are unpredictable.


Anyhow, a Comparable isn’t a Comparable any more, it’s a Comparable, and an Integer isn’t a Comparable any more, it’s a Comparable, and you’re going to get unsafe-comparison whines every time you try to compile anything (and worse, your API’s customers will too).

Then when you try to paramaterize it all with generics you’ll discover that Comparable is kind of surprising, and then you’ll discover there are all sorts of problems with arrays of parameterized types. Anyhow, after pursuing a maze of twisty little Java-Generics passages around the Internet (I read Gilad’s explanation of the unsafeness of generic arrays seven or eight times, even), I stumbled on the key resources to explain this stuff: Peter Williams of Sussex University on Generic arrays, and this excerpt from Java in a Nutshell by David Flanagan, which I totally have to buy. To summarize, the key incantations are:

public interface Page<K extends Comparable<K>>
public class LocalPage<K extends Comparable<K>> implements Page<K>
Pair<K>[] p = (Pair<K>[]) new Pair[size];


On that last one, you have to be prepared to ignore the unchecked-cast warning (and it would be good to read Gilad’s piece so you understand why it happens).

Comments

Popular posts from this blog

How to Fix a Jammed Toyota Camry Trunk

Web 2.0 and Research

[Research] Famous Rejected Papers