15 October 2009

Little confusion about Generics

Lets consider some class used for collecting References. It requires little work but there is way to do not determine Reference type to early. So lets observe consequences of this action.

import java.lang.ref.Reference;
import java.lang.ref.WeakReference;

 * Collects {@link Reference}-s
public class ReferenceCollector<Ref extends Reference</* ? extends */ Type>, Type>
    implements Iterable<Reference<? extends Type>> { ... }

This class will allow given code to compile:

ReferenceCollector<WeakReference<String>, ?> rc1 = null;
ReferenceCollector<WeakReference<String>, ? extends Object> rc2 = null;

On the other hand reversing Type arguments will be not allowed:

ReferenceCollector<WeakReference<? extends Object>, String> rc2 = null;

This mean that nesting is count more then arguments order, what more it's all about compatibility not as I would expect equality of types. Probably I just need read rest of JLS when I'll have free time to get idea why '?' is allowed as second generic argument.

0 comments / komentarz(y):

Post a Comment