如何从此哈希表中获取信息

sin*_*rem 0 java swing hashtable arraylist

我试着保持这个简单,但仍然可以理解.如果有任何困惑,请告诉我!

我得到了这个哈希表:

private Hashtable<String, ArrayList<String>> allChannels = new Hashtable<String, ArrayList<String>>();
Run Code Online (Sandbox Code Playgroud)

我正在使用此方法插入客户端/用户:

public void connectChannel(String username, String channel) throws RemoteException{
    allChannels.put(channel, new ArrayList<String>());
    allChannels.get(channel).add(username);
}
Run Code Online (Sandbox Code Playgroud)

现在我想使用这个方法,以获得一个连接到给定通道(参数)的用户的arraylist.怎么可以这样做?

@Override
public ArrayList<String> getUsersInChannel(String channel) throws RemoteException{
    return **Code needed**   
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

编辑:顺便说一句,连接方法得到了几个检查,但它很长,所以我没有打扰它,因为我知道它的工作很好.

编辑:因为使用return allChannels.get(channel)似乎是正确的,所以我的JList还有其他问题.我在GUILogic中使用了这些方法来运行JList.我已经使另外两个JList以相同的方式工作了.

DefaultListModel usersInChanDLM = new DefaultListModel();

public DefaultListModel getUsersInChannelAsDefaultListModel() throws RemoteException{
    if(!(getChannel() == null)){
        for(String a : cf.getUsersInChannel(getChannel())){
            usersInChanDLM.addElement(a);
            System.out.println(a);
        }
    }
    return usersInChanDLM;
}

void updateUsersInChannelJlist(JList jList3) throws RemoteException {
    usersInChanDLM.clear();
    usersInChanDLM.removeAllElements();
    for(Client c : cf.getClients()){
        if(!(usersInChanDLM.contains(c.findName()))){
            usersInChanDLM.addElement(c.findName());
        }
    }
    jList3.setModel(usersInChanDLM);
}
Run Code Online (Sandbox Code Playgroud)

因此,我很明显能够看到最后一种方法是搞砸了这个,因为它添加了列表中的所有客户端.但它应该说什么呢?

解:

所以,我做到了!

    public void updateUsersInChannelJlist(JList jList3) throws RemoteException {
        usersInChanDLM.clear();
        usersInChanDLM.removeAllElements();
        for(String s : cf.getUsersInChannel(channel)){
            if(!(usersInChanDLM.contains(s))){
                usersInChanDLM.addElement(s);
            }
        }
        jList3.setModel(usersInChanDLM);
   }
Run Code Online (Sandbox Code Playgroud)

Gen*_* S. 5

或者我错过了一些非常明显的东西,或者你只是忽略了答案(你已经在代码中已经有了!)

return allChannels.get(channel);
Run Code Online (Sandbox Code Playgroud)

你应该考虑的一件事是,如果你一遍又一遍地调用这个connectChannel方法,你将不断地破坏你的arraylist(因为你每次调用该方法时都会调用new),所以实际上每个通道都注定要失败在任何时候都有一个用户.

您应该检查数组列表是否为空,如果不是,请不要重新实例化它(除非我错过了您尝试做的事情,我很可能会这样做).