Dataset for storing objects in java

Let's say I have a few objects to save:

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

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

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

The way they are saved can also affect future expansion β€” in the future, these objects can be generated by fields from SQL Server. (It’s also an Android app, so this could be a factor.)

+4
source share
4 answers

You will need a List<Person> . Your diagram offers inheritance, so you want to have a superclass collection 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, expressed, will not allow engineers to be Customers or sales engineers to enter the field, but it is a curse of inheritance in cases like yours.

A better design, if you need flexibility, might be to keep the Person class and assign the Person role in the style of the decorator.

The decorator will add behavior using composition rather than inheritance, for example:

 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 } } 
+5
source

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

+4
source

If you are not sure how you will need to access objects in the future, you may find that HashTable <Person> provides a wide degree of flexibility.

Since it uses key-value pairs, you can quickly get a specific object, and the .keys () method offers a means to move around the entire set iteratively if you find it necessary.

+2
source

I assume all objects are part of a set?

Ideally, the person should have get / setCustomer, and Employee should have get / setFieldEngineer, and then the structure should look something like this:

 class CustomerRelationship{ public Employee employee; public SalesEngineer salesEngineer; public Person customer; } 

If the objects are not part of the set, but are a list of the object, then you can revise your design. Or you can use instanceof everywhere (bad).

0
source

All Articles