ArrayToCollection(ia, cn);// T inferred to be Number
fromArrayToCollection(fa, cn);// T inferred to be Number
fromArrayToCollection(na, cn);// T inferred to be Number
fromArrayToCollection(na, co);// T inferred to be Object
//test.fromArrayToCollection(na, cs);// 错误用法
}
public <T> void fromArrayToCollection(T a, Collection<T> c) {
for (T o : a) {
//如果参数定义为 Collection< ? > c 以下写法错误
c.add(o); // compile time error
}
}
/**
* generics 嵌套用法
* @param shapes
*/
public void drawAll(List< ? extends Shape> shapes) {
List<List< ? extends Shape>> history = new ArrayList<List< ? extends Shape>>();
history.add(shapes);
for (Shape s : shapes) {
s.draw();
}
}
/**
*
*
*/
public void Test4() {
List<String> l1 = new ArrayList<String>();
List<Integer> l2 = new ArrayList<Integer>();
System.out.print(l1.getClass() == l2.getClass());
//打印为 true,
}
/**
* 错误用法
*/
public void Test5() {
Collection cs = new ArrayList<String>();
//以下为错误用法
//if (cs instanceof Collection<String>) { } // illegal
//以下为警告用法
//Collection<String> cstr = (Collection<String>) cs; // unchecked
// warning
}
public void Test6() {
//错误用法
//List<String> lsa = new List<String>; // not really allowed
List< ? > lsa = new List< ? >; // ok, array of unbounded wildcard
// type
Object o = lsa;
Object oa = (Object) o;
List<Integer> li = new ArrayList<Integer>();
li.add(new Integer(3));
oa = li; // correct
//String s = lsa.get(0); // run-time error - ClassCastException
//String s = lsa.get(0); // run time error, but we were warned
String s = (String) lsa.get(0); // run time error, but cast is
// explicit
}
public void Test7() {
Sink<Object> s = null;
Sink<String> s1 = null;
Collection<String> cs = null;
String str = writeAll(cs, s1);
//String str = writeAll(cs, s); // 无效调用
Object obj = writeAll1(cs, s); // 正确的调用
str = writeAll2(cs, s1); // 正确的调用
}
public <T> T writeAll(Collection<T> coll, Sink<T> snk) {
T last = null;
for (T t : coll) {
last = t;
snk.flush(last);
}
return last;
}
public <T> T writeAll1(Collection< ? extends T> coll, Sink<T> snk) {
T last = null;
for (T t : coll) {
last = t;
snk.flush(last);
}
return last;
}
public <T> T writeAll2(Collection<T> coll, Sink< ? super T> snk) {
T last = null;
for (T t : coll) {
last = t;
snk.flush(last);
}
return last;
}
// 打印
private void log(Object ob) {
System.out.print(ob);
}
}
//辅助定义
abstract class Shape {
public abstract void draw();
}
class Circle extends Shape {
private int x, y, radius;
public void draw() {
}
}
class Rectangle extends Shape {
private int x, y, width, height;
public void draw() {
}
}
class Person {}
class Driver extends Person {}
class Census {
public static void addRegistry(Map<String, ? extends Person> registry) {
}
public static void add(List< ? exten