简体   繁体   中英

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> . ie only List (which is an interface) is accepted.

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<? 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. If you want to force using of ArrayList then use

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. 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>> )

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<? extends List<URL>> List<? extends List<URL>> is you are stoned.

Can we return the previously declared announces as a List<List<URL>> ? Sure, why not. Just do a cast, we know it's safe. What if caller inserts a LinkedList<URL> into it? Who cares?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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