Tuesday, October 18, 2011

Generic

Generic can be placed in class/interface declaration, variable declaration, method parameter or method return value.

In method return value :
public static <B> List<B> aMethod() {...} // any reference can replace B.

In method parameter :
public static <B> List<B> aMethod(B b) {...} // any reference can replace B.
public <B> void aMethod(B b) {...} // any reference can replace B
public <B extends Number> void aMethod(B b) {...} // B must be subclass of Number

In variable declaration :
List<String> list = new ArrayList<String>(); // list of String, no other type

In interface or class declaration :
interface IDao <X extends IEntity> {...} // X must be subclass of IEntity
interface IBidDao extends IDao<Bid> // Bid replaces X and Bid is subclass of IEntity
class BaseDao<X extends IEntity> implements IDao<X> // BaseDao takes X which is then substitutes X in IDao

We can put ? to replace B or X above, which also means any but with restrictions:

List<?> list = new ArrayList<Integer>(); means any class can fit in, and as for List, we can't add object to the list. In general, all of the methods in List that take the generic object as parameter are not applicable (compile error as in add, addAll, etc).

List<? extends Number> list = new ArrayList<Integer>(); means any class that extends Number can fit in, and as for List, we can't add object to the list. In general, all of the methods in List that take the generic object as parameter are not applicable (compile error as in add, addAll, etc).

List<? super Number> list = new ArrayList<Object>(); means any class on top of Number inheritance hierarchy can fit in, and as for List, we can add object to the list as opposed to <?> or <? extends Number>.

The ? and super keyword in generic only apply to variable declaration or method parameter not to class declaration:
List<? extends Number> list = new ArrayList<Integer>();
public void aMethod(List<? extends Number> list) {...}

0 comments:

 

©2009 Stay the Same | by TNB