Skip to content

Better Java Generics

I’ve been doing my fair share of C++ lately, and I had to switch back to Java for this project in a class I’m taking. I created a nice little Pair class, almost exactly like I would in C++, but then I created some helper functions that create a Pair, and realized that generics suck in Java. Why? Well, because there not a full template (generic) implementation. See, if they where templates, I’d be able to do exactly what I wanted, and have a method template (if you don’t know what that is, read the blurb at the bottom). The beauty of a template method, is you can create a generic function, that you can pass in some arbitrary argument, and it spits out something fantastically formatted how you specified. Now, there are in fact ways around some of this, like having an out parameter that is already initialized to the type you want to return, but that’s a crappy solution.

So, why isn’t there a full templates implementation in Java? Well, for one, generic classes are the only thing you’ll ever need 9/10ths of the time, for one. Based on how Java is structured, it’s also a little more difficult (I think?) than it is in C++, and Sun is more concerned with giving you the kitchen sink than a universal remote.

So, for all of you who don’t know what method templates are, there this wonderful thing where you have a method, and it simply performs an operation on any type that that operation can be performed on. The easy example, is a max() function. In Java, you’d have a separate definition for every type which you want to check for a max value. In C++ however, you do something like this:

TYPE max(TYPE a, TYPE b)
  return (a > b ? a : b);

And when you call it, you just specify the type it’s operating with, like so:

double a = 10.6;
double b = 11.8;
double maxVal = max(a, b);

And that will, quite simply, return 11.8. And you can do that with integers, floats, anything that implements the > operator.

Be Sociable, Share!

Posted in Programming. Tagged with , .

0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.