在集合中,經常可看到<?>,<? extends E>,<? super E>,它們都是屬於泛型;
<?>:
是泛型通配符,任意類型,如果沒有明確,那么就是Object以及任意類型的Java類;
<? extends E>:
向下限定,E及其子類,表示包括E在內的任何子類;
<? super E>:
向上限定,E及其父類,表示包括E在內的任何父類;
示例如下:
class Animal {} class Dog extends Animal {} class Cat extends Animal {} public class CollectionDemo { public static void main(String[] args) { Collection<?> c1 = new ArrayList<Animal>(); Collection<?> c2 = new ArrayList<Dog>(); Collection<?> c3 = new ArrayList<Cat>(); Collection<?> c4 = new ArrayList<Object>(); Collection<? extends Animal> c5 = new ArrayList<Animal>(); Collection<? extends Animal> c6 = new ArrayList<Dog>(); Collection<? extends Animal> c7 = new ArrayList<Cat>(); // Collection<? extends Animal> c8 = new ArrayList<Object>(); Collection<? super Animal> c9 = new ArrayList<Animal>(); // Collection<? super Animal> c10 = new ArrayList<Dog>(); // Collection<? super Animal> c11 = new ArrayList<Cat>(); Collection<? super Animal> c12 = new ArrayList<Object>(); } }
在上述代碼中,c1,c2,c3,c4中<?>代表任意類型,c5,c6,c7中<? extends Animal>代表包括Animal在內的任何子類;而c8中,Object是所有類的基類,Animal是它的子類,<? extends Animal>只包含Animal及其子類,所以這里會編譯報錯;c9,c10,c11,c12中<? super Animal>表示包含Animal及其父類,c10,c11這里會編譯報錯;