0

See title. I can't figure out why it doesn't work.

Example of non-working code:

displayList(subclassArrayList);

...gives me

"incompatible types: ArrayList<B> cannot be converted to ArrayList<A>"

My classes:

public static class A{
    int someAttribute = 0;
    A(){}
}
public static class B extends A{
    int someOtherAttribute = 2;
    B(int value){
        this.someOtherAttribute = value;
    }
}

Somewhere in main:

ArrayList<B> subclassArrayList = new ArrayList();
subclassArrayList.add(new B(3));
subclassArrayList.add(new B(5));
subclassArrayList.add(new B(7));

The offending function:

void displayList(ArrayList<A> superclassList){
    for(A item : superclassList){
        System.out.print(item.someOtherAttribute);
        System.out.print(" ");
    }
}

However, I've found that I'm able to do this with no apparent problems.

ArrayList<A> superclassArrayList = new ArrayList();
superclassArrayList.addAll(subclassArrayList);
displayList(superclassArrayList);

What exactly is my code doing behind the scenes, here?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Because you declare `ArrayList` and in your loop you use another Type `A`, so try to change this : `for(A item : superclassList){` to this : `for(B item : superclassList){` – Youcef LAIDANI Jan 12 '17 at 18:50
  • Another duplicate question: [Why are arrays covariant but generics are invariant?](http://stackoverflow.com/questions/18666710/why-are-arrays-covariant-but-generics-are-invariant) – Ted Hopp Jan 12 '17 at 18:50

0 Answers0