Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Control selected items of an ArrayList [closed]

Tags:

java

arraylist

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:

  • Add a boolean field 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.
  • Extends Client into SelectableClient, and add the boolean field selected.
  • Have a secondary array (or ArrayList, or whatever) which controls the selected status.
  • Use a 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?

like image 897
moictab Avatar asked Feb 28 '26 00:02

moictab


2 Answers

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

like image 134
aioobe Avatar answered Mar 02 '26 13:03

aioobe


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.

like image 25
ralfstx Avatar answered Mar 02 '26 15:03

ralfstx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!