Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use addAll() with different types

I have a course project and I am not able to solve the following problem:

I need to create a linkedlist in which I can add a list of elements from a class called Person, and a list of elements from a class called Accounts using addAll()

List<Person> persons= new LinkedList<Person>();
List<Accounts> accounts= new LinkedList<Accounts>();
List<???> elements = new LinkedList<>();
elements.addAll(persons);
elements.addAll(accounts);

My teacher ordered to make a class ElementsOfTheBank to fill the place with ???, but I couldn’t understand how to make it work 🙁

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need a common type that is shared by all elements of the bank. Trivially, java.lang.Object is common to them all, but perhaps you’re being asked to make e.g. public interface ElementOfBank, so that you can then declare your Person class as class Person implements ElementOfBank {}.

Once you’ve done that, you can declare your list to be of that element: List<ElementOfBank> elements = ...;, and you could call .addAll(persons) on such a list. After all, every person instance is also an ElementOfBank, that’s what class Person implements ElementOfBank means.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading