标签:
1.使用泛型方法可以取代将整个类泛型话,要定义泛型方法,只需将泛型参数列表至于返回值之前:public class GenericMethods { public <T> void f(T x) { System.out.println(x.getClass().getName()); } public static void main(String[] args) { GenericMethods gm = new GenericMethods(); gm.f(""); gm.f(1); gm.f(1.0); gm.f(1.0F); gm.f('c'); gm.f(gm); } }
public class GenericVarargs { public static <T> List<T> makeList(T... args) { List<T> result = new ArrayList<T>(); for (T item : args) result.add(item); return result; } public static void main(String[] args) { List<String> ls = makeList("A"); System.out.println(ls); ls = makeList("A", "B", "C"); System.out.println(ls); ls = makeList("ABCDEFFHIJKLMNOPQRSTUVWXYZ".split("")); System.out.println(ls); } }3.边界使你可以在用于泛型的参数类型上设置限制条件。
public class GenericsAndCovariance { public static void main(String[] args) { List<? extends Fruit> flist = new ArrayList<Apple>(); // Compile Error: can't add any type of object: // flist.add(new Apple()); // flist.add(new Fruit()); // flist.add(new Object()); flist.add(null); // Legal but uninteresting // We know that it returns at least Fruit: Fruit f = flist.get(0); } }5.<? super T>这里比较容易使用,没<? extends T>这么多限制,这里的意思是,以T类为下限的某种类,
标签:
原文地址:http://blog.csdn.net/zdp072/article/details/44024981