0

I don't understand. Why will this not compile? Just adding Beagles works fine. c is declared as super Beagle which should include Dog.

public class Hello<T> {

   public static void main(String[] args){

    Dog d = new Dog();

    ArrayList<? super Beagle> c = makeArrayList(d);

    c.add(new Beagle());
    c.add(new Beagle());
    c.add(new Dog());    
  } 

  public static <G extends Animal> ArrayList<G> makeArrayList(G g){
    ArrayList<G> genlist = new ArrayList<>();
    genlist.add(g);
    return genlist;

 }
}


class Animal{public void makeSound(){
        System.out.println("Sound!");
 }
}   
 class Dog extends Animal{}
class Beagle extends Dog{}
MadMax
  • 605
  • 1
  • 6
  • 19
  • That answer talks about the theory, thats great but Its doesn't answer the question "Why this doesn't compile" – MadMax Jun 27 '17 at 19:16
  • [Here's](http://docs.oracle.com/javase/specs/jls/se8/html/jls-18.html) the Java Language Specification chapter on type inference. It's too broad to be included in a SO answer. The acceptable answer is _The reasoning here is that unlike `Collection extends Thing>`, `Collection super Thing>` can always hold a `Thing` no matter what the actual parameterized type is. Here you don't care what is already in the list as long as it will allow a Thing to be added; this is what `? super Thing` guarantees_, as expressed in the accepted answer in the duplicate. – Sotirios Delimanolis Jun 27 '17 at 19:56
  • The variable `c` of type `ArrayList super Beagle>` could possibly hold an instance of `ArrayList`, `ArrayList`, `ArrayList`, or `ArrayList`. If it happened to be set to an `ArrayList`, it would violate the generic type to add a `Dog` to it. The compiler can't track what you actually assign to the `ArrayList super Beagle>` variable over the course of the program, so it assumes the worst and prevents the possible type safety violation. – Sean Van Gorder Jun 27 '17 at 20:37
  • thanks Sean! that was very clear – MadMax Jun 28 '17 at 17:07

0 Answers0