Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a 'list of cherry cokes' a 'list of cokes'?

Tags:

java

generics

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());
  }
}
like image 325
Adrian Panasiuk Avatar asked Nov 15 '12 00:11

Adrian Panasiuk


1 Answers

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());

like image 69
Krease Avatar answered Oct 29 '22 04:10

Krease