Maximus Decimus Maximus Decimus - 1 month ago 4
Java Question

Difference between a LinkedList of an interface and a collection of certain type as parameter

I have a class that represents a model like this:

public class Employee implements IEntity {

then a collection of employee

public class Employees extends LinkedList<Employee> {

then a service

public class Service {
public void transform(LinkedList<IEntity> collection){


This method is supposed to be used as generic, so I cannot explicitly write it as of type Employees, so when I try to do this

Employees employees = new Employees();
Service service = new Service();

I receive an error "The method transform(LinkedList) in the type Service is not applicable for the arguments (Employees)"

So I wonder if employees extends from LinkedList of Employee which at the same time extends from IEntity why I cannot pass it directly as parameter of the method transform?


The reason for this is that a LinkedList<Employee> is different from a LinkedList<IEntity>.

Suppose there's another class Customer that implements IEntity. You can add a Customer to a LinkedList<IEntity> but not to a LinkedList<Employee>. So there's no way that LinkedList<Employee> could be a subtype of LinkedList<IEntity>.

Consider using the type LinkedList<? extends IEntity> in place of LinkedList<IEntity>. This type is a supertype of LinkedList<Employee>. You'll then have

public class Service {
   public void transform(LinkedList<? extends IEntity> collection){


and you can happily pass your LinkedList<Employee> into that.