简体   繁体   English

这到底是什么意思收藏<? extends E> C

[英]What exactly does this mean Collection<? extends E> c

Some times, well a lot of times I see this thing occurring in the documentation.有时,很多时候我在文档中看到这件事发生。 It leaves me wondering what to type.这让我想知道该输入什么。 Could someone explain to me the meaning of this in clear dumbed down text :D.有人可以用清晰的简化文本向我解释这个的含义:D。 How this:这是怎么做的:

ArrayList(Collection<? extends E> c)

end up to be used as this:最终被用作:

new ArrayList<>(Arrays.asList("a","b","c"));

so I don't need to ask this "question" anymore by googling it, but being able to figure it out by myself.所以我不再需要通过谷歌搜索来问这个“问题”,而是能够自己弄清楚。

The syntax ? extends E 语法? extends E ? extends E means "some type that either is E or a subtype of E". ? extends E表示“是E或E的子类型的某种类型”。 The ? ? is a wildcard. 是通配符。

The code Arrays.asList("a","b","c") is inferred to return a List<String> , and new ArrayList<> uses the diamond operator, so that yields an ArrayList<String> . Arrays.asList("a","b","c")代码Arrays.asList("a","b","c")返回List<String> ,而new ArrayList<>使用菱形运算符,从而产生ArrayList<String>

The wildcard allows you to infer a subtype -- you could assign it to a reference variable with a supertype: 通配符允许您推断子类型-您可以将其分配给具有超类型的引用变量:

List<CharSequence> list = new ArrayList<>(Arrays.asList("a","b","c"));

Here, E is inferred as CharSequence instead of String , but that works, because String is a subtype of CharSequence . 在这里,将E推导出为CharSequence而不是String ,但这是可行的,因为StringCharSequence的子类型。

List<String> testList1 = new ArrayList<>(Arrays.asList("a","b","c"));

This statement creates an entirely new ArrayList object that contains the same elements as the list generated using Arrays.asList("a","b","c").此语句创建一个全新的 ArrayList 对象,该对象包含与使用 Arrays.asList("a","b","c") 生成的列表相同的元素。

Therefore, the new ArrayList and the original String list are completely independent objects.因此,新的 ArrayList 和原来的 String 列表是完全独立的对象。

FYI : Arrays.asList(arrAgument);仅供参考:Arrays.asList(arrAgument); This creates a immutable/ unmodifiable list.We cannot be altered by adding or removing items because the underlying String array's length cannot be changed at run time.这将创建一个不可变/不可修改的列表。我们不能通过添加或删除项目来更改,因为底层 String 数组的长度不能在运行时更改。 if you try to do add or remove a java.lang.UnsupportedOperationException will be thrown at run time.如果您尝试添加或删除 java.lang.UnsupportedOperationException 将在运行时抛出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM