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

Why does the following code not 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 as follows:

 Type mismatch: cannot convert from ArrayList<ArrayList<URL>> to <List<List<URL>> 
+6
java generics
source share
4 answers

Since your Generic is limited to type List<URL> . those. only List (which is an interface) is accepted.

You can resolve any list using wildcards .

 List<? extends List<URL>> announces; 

You may 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 because the Generic type takes the values List<URL> and ArrayList , LinkedList is-a List .

+16
source share

try it

 List<? extends List<URL>> announces = new ArrayList<ArrayList<URL>>(); 
+3
source share

Because your type selection is wrong.

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

Must work. It doesn't matter what type of list you use. If you want to force the use of an ArrayList, use

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

In the first example, in the list of arrays you can insert a list of arrays and there should not be any problems, but you cannot change the declared type check. What you say when you declare your variable is that I want to allow all kinds of lists, but then the list you set in it only allows ArrayLists. It makes sense?

0
source share

do

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

Using interfaces for variables is nonsense. Obviously, you are going to insert material into it, do yourself a favor, use the exact types, and you will be happy. (You cannot paste)

Now, if we expose this thing, for example, return it from a method, then it becomes a problem what the correct type should be. List<List<URL>> is perfect. List<? extends List<URL>> List<? extends List<URL>> You stoned.

Is it possible to return the previously declared announces as List<List<URL>> ? Of course, why not. Just do the actors, we know it's safe. What if the caller inserts a LinkedList<URL> into it? Who cares?

-one
source share

All Articles