【发布时间】:2014-01-27 01:06:13
【问题描述】:
我目前正在开发一个客户端/服务器应用程序,并且我正在使用 HashMap 来识别每个客户端。客户端将两个值传递给服务器 - id 和 x。我使用id 作为我的键,对于HashMap 中的每个元素,我想使用x 的值将具有匹配键id 的特定元素添加到值中。
我有以下代码:
HashMap<Integer, Integer> clients = new HashMap<Integer, Integer>();
int x;
sock = serv.accept();
in = new ObjectInputStream(sock.getInputStream());
in2 = sock.getInputStream();
out = new ObjectOutputStream(sock.getOutputStream());
int id = in2.read();
System.out.println("id = " + id);
Object o = in.readObject();
System.out.println("Server received " + o);
if (o instanceof Integer) {
x = ((Integer) o).intValue();
clients.put(id, 0 + x); //doesn't work, I need to be able to add to the existing value instead of overwriting the value
} else if (o instanceof String) {
clients.put(id, 0);
}
out.writeObject(clients.get(id));
out.flush();
有人可以帮我吗?
【问题讨论】:
-
添加是指在数学上下文中添加,或者您想添加一个与该键映射的值
-
我的意思是在数学方面。例如,如果客户端第一次通过 1 和 3,服务器应该返回 3。如果客户端第二次通过 1 和 5,服务器应该返回 8。但是,如果客户端通过 2 和 7,服务器应该返回 7,因为 2 与 1 不同。
标签: java hashmap client-server