Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data set for storing objects in java

Let's say I have multiple Objects to be stored:

Person ------------ Employee ------------ Sales Engineer       
  |                    |
Customer          Field Engineer

So: Person, Customer, Employee, Sales Engineer, Field Engineer.

I need to keep track of all of these...what is the best way to store them? In an ArrayList? A custom ArrayList?

The way they are stored also may affect future expansion - in the future, these objects might be generated by fields from an SQL Server. (Also, this is an Android App - so that could be a factor.)

like image 858
Cody Avatar asked Dec 22 '22 11:12

Cody


2 Answers

You'll want a List<Person>. Your diagram suggests inheritance, so you'll want to have a collection of the super class and let polymorphism do the rest.

Your code can do this:

List<Person> people = new ArrayList<Person>();
// Any class that extends person can be added
people.add(new Customer());
people.add(new FieldEngineer());
for (Person person : people) {
    System.out.println(person);
}

Your design as expressed won't allow Engineers to be Customers, or Sales engineers to go into the Field, but that's the curse of inheritance in cases like yours.

A better design, if you need the flexibility, might be to keep the Person class and assign a Person a Role in decorator fashion.

A decorator would add behavior using composition rather than inheritance, like this:

public class Customer {

    private Person person;

    public Customer(Person p) { this.person = p; }

    public void buyIt() { // do something customer like here }
}

public class FieldEngineer {

    private Person person;

    public FieldEngineer(Person p) { this.person = p; }

    public void fixIt() { // do something field engineer like here }
}
like image 66
duffymo Avatar answered Jan 06 '23 15:01

duffymo


Use a heterogenous list -- in java you can use generics like this List <Person>

like image 24
Sai Avatar answered Jan 06 '23 14:01

Sai