sammyukavi
sammyukavi

Reputation: 1511

Pass Arraylist of child objects and parent objects to the same method

I have class B that extends Class A. How can I write a method in Class C that can receive An ArrayList that contains objects of class B or class A without overriding?

public class A {
    //Some methods here
}

public class B extends A {
    //Some methods here
}

public class C {

    public Static void main(String[] args){
        ArrayList<A> one = new ArrayList<>();
        one.add(new A());

        ArrayList<B> two = new ArrayList<>();
        two.add(new B())

        doStuff(one);
        doStuff(two);
    }

    public void doStuff(args){
       //go ahead do stuff
    }
}

Upvotes: 1

Views: 2103

Answers (2)

John Kugelman
John Kugelman

Reputation: 361595

Use generics with a wildcard to say you'll accept a list of anything that is A or extends A.

public void doStuff(List<? extends A> list) {
    ...
}

If you want to capture the exact list type you'd write:

public <T extends A> void doStuff(List<T> list) {
    ...
}

Then you could use T inside the method. If you don't need T, stick with the first method.

Upvotes: 10

GhostCat
GhostCat

Reputation: 140427

This should work:

public void doStuff(List<? extends A) someList)

... and then, this becomes possible:

List<A> ones = new ArrayList<>();
one.add(new A());

List<B> two = new ArrayList<>();
two.add(new B())

doStuff(one);
doStuff(two);

One other important thing here: use List as your type. You only specify the specific implementation class when creating lists, but in any other place, avoid the actual class name!

Upvotes: 0

Related Questions