Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

generics

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>>
like image 215
Georg Schölly Avatar asked Mar 08 '11 08:03

Georg Schölly


2 Answers

Because your Generic is bounded to a type List<URL>. i.e. 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.

like image 62
Buhake Sindi Avatar answered Oct 16 '22 13:10

Buhake Sindi


Try this

List<? extends List<URL>> announces = new ArrayList<ArrayList<URL>>();
like image 38
Boris Pavlović Avatar answered Oct 16 '22 13:10

Boris Pavlović