我想制作像
这样的结果{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);
}
答案 0 :(得分:0)
问题在于,无论房间是什么,您总是使用相同的客户HashMap
,您需要为每个新房间动态创建地图。
您不需要在client
语句之前声明if
变量,而是可以在需要时声明变量(在本例中为if
和else
)。
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
,添加客户端,然后将该空间添加到服务器。