tags:

views:

65

answers:

1

Hello, i have a List

List<DataClient> listDataClient;

My class DataCLient:

Client client;
List<String> phoneNumber;

i have a second list

List<DataPhoneNumber> listPhoneNumber;

My class DataPhoneNumber:

String phoneNumber;
List<Client> client;

In my code i put data in my first list but now i want to reverse my list in the second. In the first list i have a Client wiht x NumberPhone now i want to have NumberPhone for x Client

+1  A: 

It sounds like you're trying to model a many-to-many relationship.

One approach would be to create a class to explicitly represent this relationship: PhoneNumberAssociation; e.g.

public class PhoneNumberAssociation {
  private final Set<Client> clients;
  private final Set<String> phoneNumbers;

  public void addClient(Client client) {
    this.clients.add(client);
  }

  public void addPhoneNumber(String phoneNumber) {
    this.phoneNumbers.add(phoneNumber);
  }
}

I tend to favour this approach when their is no obvious parent or child role in the relationship. It is also simpler than embedding lists in multiple objects and having to chain calls to add / remove based on whether a phone number is being added to / removed from a client (or conversely if a client is being added to / removed from a phone number).

Adamski
Should it really have Sets?
aioobe
yes look like many-to-many relationship.
Mercer
Sets are more suitable IMHO as they prevent duplicates. People tend to use lists out of habit despite ordering not always being required. I'm making an assumption here of course; the OP may claim differently.
Adamski
I do not know how to use your code?
Mercer
and even if you need ordering, you may use a linkedhashset. It preserves the order in which items were added
seanizer