原文出自:https://segmentfault.com/a/1190000002646193
泛型类
public class Container<K, V> { private K key; private V value; public Container(K k, V v) { key = k; value = v; } public K getKey() { return key; } public void setKey(K key) { this.key = key; } public V getValue() { return value; } public void setValue(V value) { this.value = value; } }
泛型接口
public interface Generator<T> { public T next(); }
public class FruitGenerator implements Generator<String> { private String[] fruits = new String[]{"Apple", "Banana", "Pear"}; @Override public String next() { Random rand = new Random(); return fruits[rand.nextInt(3)]; } }
泛型方法(一个基本的原则是:尽量使用泛型方法)
public static <T> void out(T t) { System.out.println(t); }
类型通配符(存在普通方法中,在不使用泛型方法时使用)
上限:<? extends T> ?是T和T的子类
下限:<? super T> ?是T和T的父类
时间: 2024-10-10 20:46:01