My Technology blog…

Juicy Java Tidbits picked up from everywhere

Java generics simplified

Posted by tanvis on August 24, 2007

Java generics. Much talked about these days. So lets take a look at what generics means. Anyone who has use java has come across the java Collections Framework.Very convenient, fun to use pass around , manipulate play with and all that. Except for one little detail So far you could add objects of any type into a collection. For example:import java.util.List;
import java.util.ArrayList;

List guestList = new ArrayList();
personList.add(”Tshah”);
personList.add(new Integer(10));

And my code will happily compile and add the two objects in. Except, this brings two major issues to the fore:

1. Java collections so far lacked any type-checking unless you implemented it manually.
2. When you access a collection element, things could go horribly wrong unless you knew which class to typecast the collection element to, causing a ton of possible runtime errors.

Generics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked. Once the compiler knows the element type of the collection, the compiler can check that you have used the collection consistently and can insert the correct casts on values being taken out of the collection. The compiler can now verify at compile time that the type constraints are not violated at run time, thereby guaranteeing more robustness.


The main difference in the two methodologies is that while in the first case the code and the compiler tell us what the developer “thinks” is true at a given point of execution in the code(which the VM checks only at run-time) versus, what a compiler “knows” and has “verified” to be true at the same given point in time.

While the primary use of generics is collections, there are many other uses. “Holder classes,” such as WeakReference and ThreadLocal, have all been generified, that is, they have been retrofitted to make use of generics. More surprisingly, class Class has been generified. Class literals now function as type tokens, providing both run-time and compile-time type information.Generics are implemented by type erasure: generic type information is present only at compile time, after which it is erased by the compiler. This is necessary to achieve total interoperability between generic code and legacy code that uses non-parameterized types (which are technically known as raw types). Doing so would however imply that parameter type information is not available at run time, meaning the new automatically generated casts may fail when interoperating with ill-behaved legacy code(One is type-checked the other is not, imagine what happens when the types dont match up?). There is, however, a way to achieve guaranteed run-time type safety for generic collections even when interoperating with ill-behaved legacy code.

This problem has been solved by adding wrapper classes to java.util.Collections which allow us to “wrap” a collection in a type-safe class and thereby provide guaranteed run-time type safety. They are similar in structure to the synchronized and unmodifiable wrappers.

Suppose you have a set of strings, s, into which some legacy code is mysteriously inserting an integer. Without the wrapper, you will not find out about the problem until you read the problem element from the set, and an automatically generated cast to String fails. At this point, it is too late to determine the source of the problem. If, however, you replace the declaration:

    Set<String> s = new HashSet<String>();

with this declaration:

    Set<String> s = Collections.checkedSet(new HashSet<String>(), String.class);

the collection will throw a ClassCastException at the point where the legacy code attempts to insert the integer. The resulting stack trace will allow you to diagnose and repair the problem. Meaning, we have now implemented type checking at the point-of-entry for previously unchecked code!

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>