0

I have a generic Item-interface and an implementation with a date property like so:

public interface Item<T extends Temporal> {
    T getDate();
}

public class SpecialItem implements Item<LocalDateTime> {
    private final LocalDateTime localDateTime;

    public SpecialItem(LocalDateTime localDateTime) {
        this.localDateTime = localDateTime;
    }

    @Override
    public LocalDateTime getDate() {
        return localDateTime;
    }
}

Now I have a provider class and interface for said Item

public interface ItemProvider<T extends Temporal> {
    List<Item<T>> getEntries();
}

public class SpecialItemProvider<T extends Temporal> implements ItemProvider<T> {
    private final List<Item<T>> entries;

    public SpecialItemProvider(List<Item<T>> entries) {
        this.entries = entries;
    }

    @Override
    public List<Item<T>> getEntries() {
        return entries;
    }
}

I have the problem that I can not really call the constructor of the SpecialItemProvider like so (I really want an object of type ItemProvider):

@Test
public void genericTest(){
    final List<SpecialItem> dateTimeList =
    Collections.singletonList(new SpecialItem(LocalDateTime.MAX)));
    ItemProvider itemProvider = new SpecialItemProvider<LocalDateTime>(dateTimeList);
}

It always fails with the following error message:

java: incompatible types: java.util.List<GenericTest.SpecialItem>
cannot be converted to java.util.List<GenericTest.Item<java.time.LocalDateTime>>

Which makes me wonder why it is not accepted although SpecialItem explicitly implements Item<LocalDateTime>

What am I doing wrong here?

FelixZett
  • 598
  • 1
  • 5
  • 14
  • @KevinEsche oh well, I'm sorry I forgot to make them all public, the code is from a short self contained example in which I made them all private inner classes. I edited my answer accordingly – FelixZett Aug 15 '16 at 09:07

1 Answers1

0

The error message makes it clear: in Java a List<SpecialItem> is not compatible with List<Item> even if SpecialItem is indeed a kind of Item. Generics in Java are invariant, so in this case you have two options:

  • (not suggested) declare dateTimeList of type List<Item> - it allows you to add SpecialItem and is compatible with the ctor signature

  • modify the ctor signature to accept a List<? extends Item<?>>

Raffaele
  • 20,627
  • 6
  • 47
  • 86
  • Could you point me into a direction how to convert the parameter of type List extends Item>> to List> because I really need the generic of the SpecialItemProvider – FelixZett Aug 15 '16 at 09:20