Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ListDataModel not work with a bounded type parameter?

I just tried to create a ListDataModel with a bounded type, like this:

DataModel<? extends Foo> model = new ListDataModel<? extends Foo>(fooList);

, where fooList is of the type List<? extends Foo>. I get the following error:

unexpected type
  required: class or interface without bounds
  found: ? extends Foo

My current workaround is to copy my data into an ArrayList<Foo>, and build a DataModel<Foo> from that, but I would like to know why this is necessary, and if there is any way to make it work?

like image 862
Björn Pollex Avatar asked Aug 29 '11 19:08

Björn Pollex


1 Answers

<? extends Foo> means "some type, I don't know which one, which is or extends Foo". When constructing the data model, you need to tell him which type of data it contains, not just one unknown type.

Just construct your data model like this:

DataModel<? extends Foo> model = new ListDataModel<Foo>(fooList);

Unfortunately, the ListDataModel<Foo> constructor only accepts a List<Foo>, and not a List<? extends Foo>. It seems to me like a misconception. For example the HashSet<E> constructor takes a Collection<? extends E> as argument. If you accept the type safety warning, just casting your list to a List<Foo> should work.

like image 176
JB Nizet Avatar answered Oct 26 '22 23:10

JB Nizet