Using inheritance with ArrayList

Hi,

I’ve been using inheritance for some of my classes, but I’ve run into some troubles when trying to do the same things with ArrayList's.

If I have 2 classes class ObjectType1 { }, class ObjectType2 extends ObjectType1 { }, and have a function void test(ObjectType1 object) { }, the function test can take in ObjectType1 or ObjectType2. For example:

class ObjectType1 {
  ObjectType1() {
  }
}

class ObjectType2 extends ObjectType1 {
  ObjectType2() {
  }
}

ObjectType1 object1 = new ObjectType1();
ObjectType2 object2 = new ObjectType2();

void test(ObjectType1 object) {
}

void draw() {
  test(object1);
  test(object2);
}

Would work fine, but when I switch everything out to ArrayList's:

class ObjectType1 {
  ObjectType1() {
  }
}

class ObjectType2 extends ObjectType1 {
  ObjectType2() {
  }
}

ArrayList<ObjectType1> object1 = new ArrayList<ObjectType1>();
ArrayList<ObjectType2> object2 = new ArrayList<ObjectType2>();

void test(ArrayList<ObjectType1> object) {
}

void draw() {
  test(object1);
  test(object2);
}

Would return an error. I could just loop through all of the ArrayList's elements, but it would be helpful to know if there was a way to have a function be able to take ArrayList<ObjectType1> and ArrayList<ObjectType2>.

Any questions or advice are appreciated,
Thanks!

1 Like

Try

void test(ArrayList<? extends ObjectType1> object) {

and welcome to the weird world of Java generics! :stuck_out_tongue_winking_eye:

Inheritance doesn’t work the same way with generics - see Generics, Inheritance, and Subtypes (The Java™ Tutorials > Learning the Java Language > Generics (Updated))

4 Likes

It works, thanks so much! Looks like I have a lot to learn! :slight_smile:

I’ve been coding Java over 15 years now and I still have to look up how generics work half the time! :smile:

1 Like