2012-01-19 26 views
1

我有一個包含用戶和頻道的聊天程序。我的下一個任務是獲取一個用戶所在的頻道列表。該怎麼做?使用Hashtable,Arraylist。從他們那裏獲取信息

這裏是代碼截至目前:

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);   
      } 
     } 
    } 
} 
+0

你可以擴展你的問題,包括變量的定義** kanal **請。如果** kanal **實際上應該是**頻道**,該方案纔有意義。 –

+0

哦,代碼通常是挪威語,但我翻譯(顯然只是它的一部分)。該變量應該是渠道,無論它說kanal ofc :) – sindrem

+0

我更正了變量+改變了方法無效,因爲我不需要返回真的 – sindrem

回答

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; 
} 
+0

非常感謝:) – sindrem

+0

你確定這可以嗎?我不應該使用枚舉來通過頻道列表嗎? – sindrem

+0

'public List getChannelsForUsername(String username){ List userChannels = new ArrayList ();對於(Enumeration e = channels.elements(); e.hasMoreElements();)如果(channels.get(channels).contains(username)){user.channels.add(channels); } } return userChannels; }' 不應該是這樣的嗎?我得到一個可怕的錯誤壽。 我不允許使用.add(頻道)。但我可以添加用戶名,這有點奇怪 – sindrem

1

有地圖

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

我不知道爲什麼你有hashTable中出現,我會盡量避免它。

同時連接用戶的信道

1)檢查是否hasmap已經有用戶 你可以得到的keySet做包含。如果有,請將channelList和新頻道添加到此列表並保存以再次映射。 2)如果這是第一道,

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

注:可能有語法錯誤,我剛纔輸入在這裏。

+0

我敢打賭,這種結構比我更好嗎? – sindrem

+0

如果散列表對業務不利,我可能會嘗試更改此代碼 – sindrem

+0

散列表是同步HashMaps。考慮到你將受到併發的影響,我會堅持Hashtable或移動到ConcurrentHashMap。 –