Home > Software design >  How to use addAll() with different types
How to use addAll() with different types

Time:11-22

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

CodePudding user response:

This is a kind of bad example, but your teacher probably wants you to use inheritance.

As a person and an account are both "elements of the bank", your classes can look like this:

class ElementsOfTheBank {
    // common variables between Person and Account
}

class Person extends ElementsOfTheBank {
    // ...
}

class Account extends ElementsOfTheBank {
    // ...
}

Then you can add both types to your list:

List<ElementsOfTheBank> elements = new LinkedList<>();
elements.addAll(persons);
elements.addAll(accounts);

CodePudding user response:

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.

CodePudding user response:

Don't use Collections just to combine correlated objects together.

It doesn't make much sense to create a List<Object> in order to Person and Account lists together. Introducing a common super of Person and Account doesn't seem to be a great idea as well. What is the advantage of binding through Inheritance a physical person and a bank account? I would rather suggest establishing the relationship between a person and their accounts through Composition (not Inheritance).

The better option would be to create a class, let's say Bank. That would encapsulate the two lists. I.e. you can introduce behavior for managing bank-clients and their accounts, and bank instance would become a single entry point for all operation you need to perform with them.

public class Bank {
    private List<Person> persons= new LinkedList<>();
    private List<Accounts> accounts= new LinkedList<>();

    // constructors, getters
    
    public boolean createAccount() {
        // TO DO ...
        return ...;
    }

    public Person findPerson(SomeProperty id) {
        // TO DO ...
        return ...;
    }
}
  • Related