Friday, July 1, 2011

Advantage of Generics

Pretty much the same way, methods and constructors can be generic if they declare one or more type variables.

public static <T> T getFirst(List<T> list)

This method will accept a reference to a List<T> and will return an object of type T.


Examples

You can take advantage of generics in both your own classes or the generic Java library classes.

Type Safety When Writing...

In the following code snippet, for example, we create an instance List<String> of populate it with some data:

List<String> str = new ArrayList<String>();
str.add("Hello ");
str.add("World.");

If we tried to put some other kind of object into the List<String>, the compiler would raise an error:

str.add(1); // won't compile

... and When Reading

If we pass the List<String> reference around, we're always guaranteed to retrieve a String object from it:

String myString = str.get(0);

Iterating

Many classes in the library, such as Iterator<T>, have been enhanced and made generic. The iterator() method of the interface List<T> now returns an Iterator<T> that can be readily used without casting the objects it returns via its T next() method.


for (Iterator<String> iter = str.iterator(); iter.hasNext();) {
  String s = iter.next();
  System.out.print(s);
}

Using foreach

The for each syntax takes advantage of generics, too. The previous code snippet could be written as:

for (String s: str) {
  System.out.print(s);
}

that is even easier to read and maintain.

Autoboxing and Autounboxing

The autoboxing/autounboxing features of the Java language are automatically used when dealing with generics, as shown in this code snippet:

List<Integer> ints = new ArrayList<Integer>();
ints.add(0);
ints.add(1);
      
int sum = 0;
for (int i : ints) {
  sum += i;
}

No comments:

Post a Comment

Chitika