简体   繁体   中英

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
    }
}

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM