//提供两种使用情况,第二种情况定义前者是后者的子类-类型通配方式
package ming; import java.util.ArrayList; import java.util.Collection; public class GenericMethodTest { static <T> void fromArraytoCollection(T[] a, Collection<T> c) { for (T o : a) { c.add(o); } } public static void main(String[] args) { // TODO Auto-generated method stub //T stand for Object Object[] oa = new Object[100]; Collection<Object> co = new ArrayList<Object>(); fromArraytoCollection(oa,co); //T stand for Number Integer[] ia = new Integer[100]; Float[] fa = new Float[100]; Collection<Number> cn = new ArrayList<Number>(); fromArraytoCollection(ia,cn); fromArraytoCollection(fa,cn); } }
package ming; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class GenericMethodTest { static <T> void fromArraytoCollection(Collection<? extends T> from, Collection<T> to) { for (T ele : from) { to.add(ele); } } public static void main(String[] args) { List<Object> ao = new ArrayList<Object>(); List<String> as = new ArrayList<String>(); // string is subclass of object fromArraytoCollection(as, ao); } }