使用Hashtable,Arraylist。从他们那里获取信息

时间:2012-01-19 12:20:35

标签: java arraylist hashtable

我有一个包含用户和频道的聊天程序。我的下一个任务是获取一个用户所在的频道列表。如何做到这一点?

以下是截至目前的代码:

ChatFrontImpl:

private Hashtable<String, ArrayList<String>> channels = new Hashtable<String, ArrayList<String>>();
private ArrayList<Client> clients;

public synchronized boolean registerClient(Client client, String password) throws RemoteException {
if(!u.logIn(client.findName(), password)){
    System.out.println("Wrong username or password!");
    return false;
}
if (!clients.contains(client)) {
    try {
        clients.add(client);
        updateJlist();
        System.out.println(client.findName() + " registered.");
    } 
    catch (Exception e){
        System.out.println("error in method registerClient(): " + e);
    }
    return true;
}else
    return false;
} 

public void connectChannel(String username, String channel) throws RemoteException{ 
    if(isUserRegistered(username)){
        if (!channels.containsKey(channel)) {
            String message = "User " + username + " entered the channel";
            channels.put(channel, new ArrayList<String>());
            channels.get(channel).add(username);
            notifyChannelSystem(channel, "SYSTEM", message);
            notifySelf(username, "Write /? for avaliable commands");
        }
        else{
            if(channels.get(channel).contains(username)){ 
            } 
            else {
                channels.get(channel).add(username);
                String message = "User " + username + " just entered the channel";
                notifyChannelSystem(channel, "SYSTEM", message);        
          }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

有地图

private HashMap<Client, channlesList> clientsAndRooms;
private ArrayList channels = ArrayList <channel>();

我不知道为什么你有哈希表,我会尽量避免它。

将用户连接到频道

1)检查hasmap是否已有该用户         您可以获取keySet并执行包含。如果有,请将channelList和新频道添加到此列表并再次保存到地图。    2)如果这是第一个频道,

channelList.add(channel);
clientAndRooms.put(userName,channelList);

注意:可能存在语法错误,我只是在这里输入。

答案 1 :(得分:1)

我会使用不同的数据结构 - 但假设您希望继续使用此结构(以回答问题):

public List<String> getChannelsForUsername(String username) {
    List<String> userChannels = new ArrayList<String>();
    for (String channel : channels.keySet()) {
        if (channels.get(channel).contains(username)) {
            userChannels.add(channel);
        }
    }
    return userChannels;
}