简体   繁体   English

为什么我不能将ArrayList分配给List变量?

[英]Why can't I assign an ArrayList to a List variable?

Why doesn't the following code work? 为什么以下代码不起作用?

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

List<List<URL>> announces;
announces = new ArrayList<ArrayList<URL>>();

The error is the following: 错误如下:

Type mismatch: cannot convert from ArrayList<ArrayList<URL>> to <List<List<URL>>

Because your Generic is bounded to a type List<URL> . 因为Generic 受限List<URL>类型。 ie only List (which is an interface) is accepted. 即只接受List (接口)。

You can allow any list by using wildcards . 您可以使用通配符来允许任何列表。

List<? extends List<URL>> announces;

You can also consider subtyping . 您也可以考虑子类型 Example: 例:

List<List<URL>> announces = new ArrayList<List<URL>>();
announces.add(new ArrayList<URL>());
announces.add(new LinkedList<URL>());

This is valid as the Generic type accepts a List<URL> and ArrayList , LinkedList is-a List . 这是有效的作为通用型接受一个List<URL>ArrayListLinkedList 是-一个 List

尝试这个

List<? extends List<URL>> announces = new ArrayList<ArrayList<URL>>();

Because your type casting is wrong. 因为你的类型转换是错误的。

List<List<URL>> announces; announces = new ArrayList<List<URL>>();

Should work. 应该管用。 Doesn't matter the type of List you use. 与您使用的List类型无关。 If you want to force using of ArrayList then use 如果要强制使用ArrayList,请使用

List<ArrayList<URL>> announces;
announces = new ArrayList<ArrayList<URL>>();

In the first example, in your array list you can insert an array list and there should be no problem, but you can't change your declared Type check, What you are saying when you declare your variable is that I want to allow all sorts of lists but then the list you are setting in it only allows ArrayLists. 在第一个示例中,您可以在数组列表中插入数组列表并且应该没有问题,但是您无法更改声明的类型检查,在声明变量时您所说的是我想允许所有排序列表,但然后您在其中设置的列表只允许ArrayLists。 Make sense? 说得通?

do

ArrayList<ArrayList<URL>> announces = new ArrayList<ArrayList<URL>>();

Use interfaces for variables is nonsense. 使用变量接口是无稽之谈。 Obviously you are going to insert stuff into it, do yourself a favor, use exact types and you'll be happy. 显然你要在其中插入东西,帮自己一个忙,使用确切的类型,你会很高兴。 (You cannot insert into a List<? extends List<URL>> ) (你不能插入List<? extends List<URL>>

Now, if we expose this thing, like returning it from a method, then it becomes a problem what should be the proper type. 现在,如果我们暴露这个东西,比如从方法中返回它,那么它应该成为一个应该是正确类型的问题。 List<List<URL>> is perfect. List<List<URL>>是完美的。 List<? extends List<URL>> List<? extends List<URL>> is you are stoned. List<? extends List<URL>>你被扔石头了。

Can we return the previously declared announces as a List<List<URL>> ? 我们可以将先前声明的announces作为List<List<URL>>吗? Sure, why not. 当然,为什么不呢。 Just do a cast, we know it's safe. 做一个演员,我们知道这是安全的。 What if caller inserts a LinkedList<URL> into it? 如果调用者将LinkedList<URL>插入其中会怎样? Who cares? 谁在乎?

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

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