Monday, July 9, 2012

Java Generics assignment sheet


raw type <------ any
any <------ raw type
<?> <------ any
<? extends T> <------ <T> and <? extends T>
<? super T> <------ <T> and <? super T>
<------: assign (assign from right to left)
any: all different variations of the generic class, including raw type and <T> and <?> and <? extends T> and <? super T>.
Example:


public class Main {


/**
* @param args
*/
public static void main(String[] args) {

List listRaw = new ArrayList();
List<Student> listQualified = new ArrayList<Student>();
List<?> listUnbounded = new ArrayList<Student>();
List<? extends Student> listUpBounded = new ArrayList<Student>();
List<? super Student> listDownBounded = new ArrayList<Student>();

// List raw type can take all different variations of List, for compatibility reason.
List rawList1 = listRaw;
List rawList2 = listQualified;
List rawList3 = listUnbounded;
List rawList4 = listUpBounded;
List rawList5 = listDownBounded;

// All different variations of List can take List raw type, for compatibility reason
listRaw = rawList1;
listQualified = rawList2;
listUnbounded = rawList3;
listUpBounded = rawList4;
listDownBounded = rawList5;

// List unbounded wildcard can take All different variations of List
List<?> wildcardList1 = listRaw;
List<?> wildcardList2 = listQualified;
List<?> wildcardList3 = listUnbounded;
List<?> wildcardList4 = listUpBounded;
List<?> wildcardList5 = listDownBounded;

// List subtype wildcard can take <T> and <? extends T> (and as mentioned above raw type)
List<? extends Student> subTypeWildcartList1 = listQualified;
List<? extends Student> subTypeWildcartList2 = listUpBounded;

// List supertype wildcard can take <T> and <? super T> (and as mentioned above raw type)
List<? super Student> superTypeWildcartList1 = listQualified;
List<? super Student> superTypeWildcartList2 = listDownBounded;

// You cannot create generic class instance with any form of wildcard
// List listNotAllowed1 = new ArrayList<?>();
// List listNotAllowed2 = new ArrayList<? extends Student>();
// List listNotAllowed3 = new ArrayList<? super Student>();

// An "exact" type of List (no wildcards) in a generic method argument can take all different variations of List.
// The return type is the same as calling the list.get(0),
// which is Object for List, List<?> and List<? super T>, and T for List<T> and List<? extends T>.
Object objectRaw = getFirstElement(listRaw);
Student studentQualified = getFirstElement(listQualified);
Object objectUnbounded = getFirstElement(listUnbounded);
Student studentUpBounded = getFirstElement(listUpBounded);
Object objectDownBounded = getFirstElement(listDownBounded);
}

public static <T> T getFirstElement(List<T> list) {
T t = list.get(0);
return t;
}
}

0 comments:

Post a Comment