简体   繁体   中英

Reverse List<Object>

List 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

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 ; eg

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM