Controlling the Selected Elements of an ArrayList
I have ArrayList
of Client
:
ArrayList<Client> clients = new ArrayList<>();
These clients are displayed in a list and the user can "select" one or more clients. This means that each client may or may not be selected, and there is no need to store this value outside of the screen where the list is displayed. I want this custom selection to work with it (like checking a checkbox in a list box), but I was wondering what is the best way to do it. What I have tried:
- Add a boolean field
selected
to the classClient
. I don't like this option as the selected is not the original propertyClient
and it doesn't make sense on it. - Expands
Client
inSelectableClient
and adds a boolean fieldselected
. - You have a secondary array (or ArrayList or whatever) that controls the selected status.
- Use a structure
Map<boolean, Client>
, but I am not sure about this option as I am adding and removing clients from the array.
Which of these options are most effective and easier to implement?
source to share
I would recommend using Set<Client>
(for example HashSet<Client>
) and adding selected clients to this set.
This avoids adding a field to Client
that doesn't really belong to that class.
Note that if you are using JList
for example you can use ListModel
/ directly ListSelectionModel
. (You don't need to create / maintain a data structure to host the selected clients yourself.)
source to share
Add boolean field selected for Client class
As you already pointed out, the selected state is not a client property, but a user property. If you have multiple users, one user can select a customer and the other cannot. Therefore, the selection must be kept in the user's area.
Usage Set<Client>
, as already suggested, seems like a better data structure as it avoids duplication and thus clients can be safely canceled with remove()
.
Extends client to SelectableClient
This approach has the same problem, the selection state is modeled as a property of the client, not the user.
source to share
I would recommend that you create a new generic class sth like this:
class SelectableItem<T> {
private T item;
private boolean selected;
public SelectableItem(T item, boolean selected) {
....
}
// getters setters
}
and create an array or set of that type. This way you only have one additional class and you can reuse it later for other use cases.
source to share