我想知道如何制作hashmap [java multi chat room]

时间:2018-03-29 14:37:48

标签: java tcp-ip

我想制作像

这样的结果
{38={mother, father}, 39={son}}

但结果就像

server={38={son, father, mother}, 39={son, father, mother}}
client={son, father, mother}

所以任何人都可以这样做

server={38={mother, father}, 39={son}}

我的代码如下

HashMap<String, DataOutputStream> clients;
HashMap<String, Object> server;

nick_name = input.readUTF();
roomnumber= input.readUTF();
if (server.containsKey(roomnumber)){
    clients.put(nick_name, output);
}
else {
    clients.put(nick_name, output);
    server.put(roomnumber,clients);
}

1 个答案:

答案 0 :(得分:0)

问题在于,无论房间是什么,您总是使用相同的客户HashMap,您需要为每个新房间动态创建地图。

您不需要在client语句之前声明if变量,而是可以在需要时声明变量(在本例中为ifelse)。

if (server.containsKey(roomnumber)) {
    @SuppressWarnings({ "rawTypes" })
    HashMap<String, DataOutputStream> clients =
            (HashMap<String, DataOutputStream>) server.get(roomnumber);
    clients.put(nick_name, output);
} else {
    HashMap<String, Object> clients = new HashMap<>();
    clients.put(nick_name, output);
    server.put(roomnumber,clients);
}

server.containsKey(roomnumber)true时,此房间已经添加,因此您使用HashMap获取server.get()并添加客户端,另一方面是条件如果未满足,则创建新的HashMap,添加客户端,然后将该空间添加到服务器。