Not new to java, but this question bothers me. I think I do not have a solid foundation.
Let's say have classes A, B, C and B extends A and C extends A. My question is, how can I define a method f() so that it can take one of List<A>, List<B> and List<C> as argument?
Use an upper-bounded wildcard:
f(List<? extends A> list)
See Oracle's tutorial for more information.
Note that this restricts you to only be able to get things out of the list in the method body; you can't call consumer methods on the list:
A item = list.get(0); // OK.
list.add(new A()); // Not OK! list might be a List<B>.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With