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 :(
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.