0

Consider the following Java Generics layout where I would expect ItemList to have a compatible interface to List:

    public interface ItemList<T extends Item> extends List<T> {}

    public interface Item {}

    public interface List<T> {}

    public static class Test<T extends Item> {

        public void foo(ItemList<T> fizz) {
            // T extends B
            // fizz is A<T extends B> extends C<T extends B>
            // therefore, is fizz not always compatible with C<B>?

            // bar(fizz); error?
            bar((List<Item>) fizz); // allowed, but unchecked cast warning?
        }

        private void bar(List<Item> buzz) {}
    }

I.e. Why am I unable to pass fizz to the bar method and why am I being warned of an unchecked cast? Is this guaranteed to be a safe cast, or is the warning a legitimate issue?

HenryK4
  • 13
  • 3
  • 2
    Who's on first? LOL Getting lost in the short class names and complicated family tree! – pczeus May 06 '20 at 23:10
  • 1
    It doesn't compile because `T` can be a subtype of `B` and Java's generics are [invariant](https://stackoverflow.com/a/18666878/1553851). – shmosel May 06 '20 at 23:14
  • Sorry! I boiled it down as much as I could but couldn't find a shorter example. – HenryK4 May 06 '20 at 23:16
  • 1
    You might want that to say `private void bar(List extends Item> buzz)`, since a `List` is not a `List`. For example, if `S` is another subtype of `Item`, then you can add an `S` to a `List` but not to a `List`. – Dawood ibn Kareem May 06 '20 at 23:30
  • 1
    `List buzz` would allow us to add *any* `Item` like `buzz.add(new YellowItem())`, but when you also have lets say `List redItems` (where `RedItem` is subtype of `Item`) should we be able to assign `buzz = redItems;`? This would allow you to add any item to `redItem`, not only red ones. For more info see [Is List a subclass of List? Why are Java generics not implicitly polymorphic?](https://stackoverflow.com/q/2745265) – Pshemo May 06 '20 at 23:45

0 Answers0