<? extends A> won't accept A's child classes
Asked Answered
J

1

10

I'm working with Android Studio and I keep getting a problem I don't know how to solve. I don't know whether it's a problem with Android Studio, with Java or a mistake a make.

I have a class whose constructor is the following:

public MakeQuery(Callable<ArrayList<? extends A>) {
     ...
}

I try to create an object of that class with the following lines:

Callable<ArrayList<B>> callable = new Callable<ArrayList<B>>() {...};
MakeQuery makeQuery = new MakeQuery(callable);

(Of course, class B extends A. Double checked)

But when I call the constructor the IDE tells me that it expects another type of argument.

What mistake am I making? Thanks for all the help! :)

Johns answered 29/6, 2015 at 19:22 Comment(5)
show all code of Callable classLives
Does the IDE tell you or the java compiler ?Ascham
The IDE tells me. I don't get to compile. And by the way, Callable is an interface that exists since JDK v 1.5. Thanks for helping!Johns
you may try Callable<ArrayList<? extends A>> callable = new Callable<ArrayList<? extends A>>() {...};Valadez
It may work but that's not what I wanted.Johns
D
11

Write Callable<? extends ArrayList<? extends A>>.

The reasons for this are complicated, but the code you wrote will only work if you pass in exactly Callable<ArrayList<? extends A>>.

The rule is that even if B extends A, Foo<B> does not extend Foo<A>. It does, however, extend Foo<? extends A>.

So apply that rule twice:

  1. List<B> doesn't extend List<A>, but it extends List<? extends A>.
  2. Callable<List<B>> doesn't extend Callable<List<? extends A>>, but it extends Callable<? extends List<? extends A>>.
Downtown answered 29/6, 2015 at 19:27 Comment(6)
This answer would be better if you explained the reason. Even if it is complicated, it's better than "seeming to work."Kurman
I agree with that. I'd love to know why this happens.Johns
The accepted answer here explains it pretty well: #4493450Pentastich
Added an explanation.Downtown
The reason for this is particularly complicated. en.wikipedia.org/wiki/…Thermy
That's some complex stuff! I guess I'll have to re-read it some times. Thanks for all the help!Johns

© 2022 - 2024 — McMap. All rights reserved.