I have an ArrayList of Client:
ArrayList<Client> clients = new ArrayList<>();
These clients are shown in a list, and the user can "select" one or more clients. That means that every client can be selected, or not selected, and there is no need to store this value out of the screen where the list is shown. I want to keep this user's choice to work with it (like setting a checkbox in the list, for example) but I was wondering what is the best way to do it. What I've tried:
selected to the class Client. I don't like this option since selected is not an original property of Client and it has not meaning on it.Client into SelectableClient, and add the boolean field selected.Map<boolean, Client> structure, but I'm not sure about this option since I add and remove clients from the arrayList.What of this options is the most efficient and easiest to implement?
I would recommend that you use Set<Client> (such as a HashSet<Client>) and add the selected clients to this set.
This avoids adding a field to Client that doesn't really belong in that class.
Note that if you're using a JList for instance, you can use ListModel/ListSelectionModel directly. (You don't need to create / maintain a data structure for holding the selected clients yourself.)
Add a boolean field selected to the class Client
As you've pointed out already, the selected state is not a property of the client, but of the user. If you have multiple users, one user may have selected a client, while another user has not. That's why the selection should be kept in the user's scope.
Using a Set<Client>, as it was already suggested, seems like the best data structure as it avoids duplicates and thus clients can safely be deselected using remove().
Extends Client into SelectableClient
This approach has the same problem, the selection state is modelled as property of the client, not the user.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With