Generics

I was just settling into a quiet evening of reviewing material for my A to Z class tomorrow when I stumbled across something quite shocking.

Mind you, I was in a fragile state, having finally released myself from a rather unhealthy personal obsession with the StringTokenizer, silently weeping (inside) while adjusting the examples to use split with regular expressions.

Back in the old days, when using some form of Java Collection, one was required to cast elements retrieved from that collection into the type of element stored in the collection. According to Sun’s site: “Besides being inconvenient, this is unsafe. The compiler does not check that your cast is the same as the collection’s type, so the cast can fail at run time.”

Generics allow you to specify the type of a objects to be stored in a collection to the compiler. This means that the compiler can confirm that you are using the collection consistently and cast the values itself as they are taken out of the collection.

What was:

ArrayList strings = new ArrayList();
strings.add("Hello World!");
String s = (String) strings.get(0);

is now:

ArrayList<String> strings = new ArrayList<String>();
strings.add("Hello World!");
String s = strings.get(0);

Frankly, the syntax is a little ugly and awkward (esp. when you start getting into collections with keys and values), but I’ll play along for now. . .


No Responses to “Generics”  

  1. No Comments

Leave a Reply