java_泛型方法使用实例

来源:互联网 发布:哪里招淘宝主播 编辑:程序博客网 时间:2024/05/29 14:17

//提供两种使用情况,第二种情况定义前者是后者的子类-类型通配方式

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 ObjectObject[] oa = new Object[100];Collection<Object> co = new ArrayList<Object>();fromArraytoCollection(oa,co);//T stand for NumberInteger[] 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 objectfromArraytoCollection(as, ao);}}


原创粉丝点击