Google

Friday, February 20, 2009

SCJP: Generics Type must be declared before use

Consider this code:



Text version:

The strangest thing about generic methods is that you must declare the type
variable BEFORE the return type of the method:

public static <k,v> mangle(Map <k,v> in)

<K,V> is the type you are going to use. But the return type is:
Map<K,V> . Even if you are not going to return anything you still
need to declare the type before use, eg:

public static <K,V> void mangle(Map in)

What happens if you change this line :

out.put(entry.getValue(), entry.getKey())

to

out.put(entry.getKey(), entry.getValue()) ?

There will be a compiler error!
This is because when you declare a new HashMap:

Map <V,K> out = new HashMap <V,K> ();

the new HashMap treats the Key as V and the Value as K,
reversing the values and keys.

It then returns the new object to the reference out which
also expects V, K, in that order.
As such when you call out.put( ), the out object expects
the V to come before the K.