ArrayList <? super Number> and Double
从http:/ / / / / typearguments.html www.angelikalanger.com genericsfaq faqsections # faq103:
A wildcard with a lower bound looks like" ? super Type" and stands
for the family of all types that are supertypes of Type , type Type
being included. Type is called the lower bound .
那么为什么
1 2 |
编译?
双类型数论是数论,但收藏指正.
1:编辑
1 2 3 4 5 6 7 8 |
你可以添加一个
1 |
不过。
想一想,然后试着创建一个能在逻辑上打破这种局面的列表。例如,您不能使用:
1 2 3 |
因为
1 2 | // Valid ArrayList<? extends Number> psupn1 = new ArrayList<Integer>(); |
…因为这是反过来的。这时你可以写:
1 |
因为列表中的任何元素都保证可转换为
Maurice Naftalin和Philip Wadler在Java泛型和集合中解释得最好:
The Get and Put Principle: use an
extends wildcard when you only get
values out of a structure, use super
wildcard when you only put values into
a structure, and don't use a wildcard
when you both get and put.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | void <T> addToList(List<? super T> list, T... things) { for (T t: things) { list.add(t); } } void <T> printList<List<? super T> list) { for (T t: list) { // doesn't compile System.out.println(t); } for (Object o: list) { // just fine System.out.println(o); } } public static void main(String[] args) { List<Object> objects = new ArrayList<Object>(); // 1, 2.0f, 3.0 autoboxed to Integer, Float, Double addToList(objects,"a string", new Object(), 1, 2.0f, 3.0); // just fine printList(objects); List<Number> numbers = new ArrayList<Number>(); addToList(numbers,"a string", new Object(), 1, 2.0f, 3.0); // doesn't compile addToList(numbers, 1, 2.0f, 3.0); // just fine printList(numbers); List<Integer> ints = new ArrayList<Integer>(); addToList(ints, 1, 2.0f, 3.0); // doesn't compile addToList(ints, 1, 2, 3); // just fine printList(ints); } |
对于任何类型的
在这里,您可以将任何
但是,如果你在这个列表上打电话给
1 2 3 4 | List<Serializable> serializables = new ArrayList<Serializable>(); serializables.add("You know String implements Serializable!"); List<? super Number> list = serializables; Object o = list.get(0); // Object is your best guess about the result's type |
也要注意,在