6

I get "Type mismatch: cannot convert from List<CherryCoke> to List<Coke<?>>"

It looks like a 'list of cherry cokes' is not a 'list of cokes'. This is counterintuitive. How can I create that 'xs' anyway, if it has to be a List<Coke<?>> and I have to have a subclass of Coke<Cherry> ?

class Taste { }
class Cherry extends Taste { }

abstract class Coke<T extends Taste> { }    

class CherryCoke extends Coke<Cherry> { }

class x {
  void drink() {
    List<Coke<?>> xs = Arrays.asList(new CherryCoke());
  }
}
Adrian Panasiuk
  • 7,249
  • 5
  • 33
  • 54
  • The most useful acronym to remember here is [PECS](http://stackoverflow.com/questions/2723397/java-generics-what-is-pecs). `Coke>` isn't anything specific, so you can't say "a list of cokes is a list of cherry cokes," but you can use `? extends Coke>`. See the question I linked for more information. – Brian Nov 15 '12 at 00:40

3 Answers3

9

You're right - a 'list of cokes' is not a 'list of cherry cokes' - a list of 'things that extend coke' is a 'list of cherry cokes' though.

You probably want to define xs as List <? extends Coke<?>> xs = Arrays.asList(new CherryCoke());

Krease
  • 15,805
  • 8
  • 54
  • 86
5

As others have pointed out, List<CherryCoke> and List<Coke<?>> are not the same thing.

But that's not really the issue here. It's not necessary to type xs as List<? extends Coke<?>>. You could have just as well created a new List<Coke<?>> and then added a new CherryCoke to it.

The error simply has to do with the compiler inferring asList's type parameter T incorrectly. If you specify T yourself it compiles:

List<Coke<?>> xs = Arrays.<Coke<?>>asList(new CherryCoke());
Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
  • This works as well. Which solution you want to use may depend on the underlying program this code is a part of. – Krease Nov 15 '12 at 00:50
4
List<Coke<?>> xs = Arrays.asList(new CherryCoke());

List<CherryCoke> is not a sub type of List<Coke<?>>(List of Coke of anything).

you should define upperbound of your generic type.

List<? extends Coke<?>> xs = Arrays.asList(new CherryCoke());
PermGenError
  • 45,977
  • 8
  • 87
  • 106
  • What's an *upper*-bound? I'd change that word to "constraint"... that's the official name, IIRC, and it's even inherently meaningful, IMHO... a "bound" sounds like theres an array under the hood, which there isn't. – corlettk Nov 15 '12 at 00:22
  • 1
    @corlettk check here please http://docs.oracle.com/javase/tutorial/java/generics/upperBounded.html – PermGenError Nov 15 '12 at 00:23
  • 4
    Pass the sauce please. I need to eat my words, and they're sour! ;-) – corlettk Nov 15 '12 at 00:25