Monday, October 31, 2005

Java Generics

J2SE 5.0 have been released for a long time. However, I didn't have time to study it. Today, I spend some time to have a look of it's new features. One new feature introduced in J2SE 5.0 is generics.

In Wikipedia, the term generics is defined as:

generics is a technique that allows one value to take different datatypes (so-called polymorphism) as long as certain contracts such as subtypes and signature are kept. The programming style emphasizing use of this technique is called generic.

For example, a List object can contains different elements String, Integer, etc. In generics, we can declare a List object only contains certain types in elements. E.g, List as a List object only contains String objects.

Generics is easily mixing up with the term template. In Java, the syntax of generics is similar to Template in C++. However, generics and Template are two different concept. Template is about code generation, and generics is about type checking. You can refer to a Wikipedia's article: Comparison of generics to templates.

With generics, it can avoid type-safe problem of collection framework of Java. However, the generics in Java is very complicated. It is not elegant. After you read the tutorial of generics, you may feel very confusing, and you may find that there are many exceptional cases need to take care when using generics in Java.

No comments: