![](/img/trans.png)
[英]How to store multiple key value pairs in Java Map as "put()" overwrites the previous data
[英]For Loop Map Overwrites Previous Value
本质上,我正在使用插槽制作棋盘游戏。 每个连接的客户端都存储在一个映射中。
当用户移动到2D数组中的坐标(即“ move 2,3”)时,应将connectionID放在该位置。
目前我的问题是,因为我有一个for循环; 当我使用move命令时,连接ID被循环中的最后一个值替换。
public void move(int x, int y) {
for (int value : gs.returnClients().values()) {
storeArray[x][y] = value;
}
}
即如果我有2个客户端连接: {62029=1, 62032=2}
和我的板子
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 2, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
假设我想让客户端1移到0,而客户端3应该是:
[[0, 0, 0, 1, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 2, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
但是我得到了:
[[0, 0, 0, 2, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 2, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
由于它会覆盖for循环中映射的最后一个值。
如何使它根据地图上的客户端“ id”移动?
编辑
在我的服务器上,我有clients.put(socket.getPort(), connectionID);
以及返回地图和ID的方法。 我有一个GameService
类,它执行命令
switch (request.type) {
case MOVE:
int clientID = Integer.parseInt(request.params[0]);
int getX = Integer.parseInt(request.params[1]);
int getY = Integer.parseInt(request.params[2]);
game.move(clientID,getX, getY);
return game.returnBoard();
在文件Request
String[] items = line.trim().split("\\s+");
switch (items[0].toUpperCase()) {
case "MOVE":
return new Request(RequestType.MOVE, items[1], items[2], items[3]);
据我了解您的代码,您需要按照以下方式进行操作:
public void move(int client, int x, int y) {
storeArray[x][y] = client;
}
其中client是gs.returnClients().values()
数字的一个(!)。 如果需要将其从该地图中取出,则需要为此提供适当的密钥,例如:
public void move(int clientId, int x, int y) {
storeArray[x][y] = gs.returnClients().get(clientId);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.