JamoBox
JamoBox

Reputation: 766

Best way to maintain a list of values in Java

I have a class that holds a list of connected clients, with their usernames being the key and the client instance being the value. So far the class looks like this:

public class ClientList {

    private static HashMap<String, Client> clients = new HashMap<>();

    /**
     * Add a client to the list of connected clients
     *
     * @param username Unique client key
     * @param client The client to add to the list
     */
    public static void add(String username, Client client) {
        clients.put(username, client);
    }

    /**
     * Remove a client from the list
     *
     * @param username the client to remove
     */
    public static void remove(String username) {
        clients.remove(username);
    }

    /**
     * Get the client in the list that has the given username
     *
     * @param username The username of the client to return
     * @return The client with a matching username
     */
    public static Client getClient(String username) {
        return clients.get(username);
    }

    /**
     * @return The client list
     */
    public static HashMap<String, Client> getList() {
        return clients;
    }

}

However, upon review of the class I realised all of these methods are simply passing params to the HashMap class, meaning the ClientList class brings nothing new to the program. Now because of that, I know I could just create a static HashMap<String, Client> somewhere and use that without having to create a whole new class for it; my issue is I don't have any suitable classes to store the list in, for example for my ClientListener class to access the list I do not want to have to statically access a class with an irrelevant name, such as ClientWriter.clientList. So my question is, what is the best way of handling this map where it maintains suitable readability?

Upvotes: 0

Views: 358

Answers (1)

lquitadamo
lquitadamo

Reputation: 653

Probably you need singleton pattern

Upvotes: 1

Related Questions