HashMap 值变得无效?
因此,我编写了这个函数,它获取用户及其位置列表(它是一个手机应用程序),它将正确的值粘贴到哈希映射中(ret.put(...)),但是一旦函数返回,所有值地图中的位置已设置为错误的用户 ID 0 和位置 0,0。在我看来,Java 正在删除 fmsg,然后删除我放置在地图中的用户 ID 和位置。你们觉得怎么样?
public HashMap<UserID, Location> getFriendsLocations(ArrayList<UserID> friends) {
MessageHdr hdr = new MessageHdr(sock);
hdr.len = 2;
hdr.id = MessageID.FRIENDS.id;
//Transmit the list of users' we are interested in
for(UserID u : friends) {
if(!hdr.send() || !u.send())
return null;
}
//Now, start receiving responses from the server.
HashMap<UserID, Location> ret = new HashMap<UserID, Location>();
FriendsMsg fmsg = new FriendsMsg(sock);
for(int i = 0; i < friends.size(); i++) {
if(fmsg.recv())
ret.put(fmsg.uid, fmsg.loc);
}
return ret;
}
So, I wrote this function which gets a list of users and their locations (it's a mobile phone app), it sticks the correct values into the hashmap (ret.put(...)) but once the function returns, all the values in the map have been set to an incorrect UserID of 0 and Location of 0,0. It seems to me that Java is deleting fmsg, which is then deleting the UserID and Location I've placed in the map. What do you guys think?
public HashMap<UserID, Location> getFriendsLocations(ArrayList<UserID> friends) {
MessageHdr hdr = new MessageHdr(sock);
hdr.len = 2;
hdr.id = MessageID.FRIENDS.id;
//Transmit the list of users' we are interested in
for(UserID u : friends) {
if(!hdr.send() || !u.send())
return null;
}
//Now, start receiving responses from the server.
HashMap<UserID, Location> ret = new HashMap<UserID, Location>();
FriendsMsg fmsg = new FriendsMsg(sock);
for(int i = 0; i < friends.size(); i++) {
if(fmsg.recv())
ret.put(fmsg.uid, fmsg.loc);
}
return ret;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
可能您的 UserID 是可变的,并且会以改变其 hashCode 和/或 equals 行为的方式发生变化。这样你就彻底搞砸了
HashMap
。Probably your
UserID
is mutable, and changes in a way changing its hashCode and/or equals behavior. This way you blow theHashMap
completely.不要将其归咎于 Java。你在这里展示的并没有说明结构是什么
或 UserID 或 Location 的使用。 fmsg.recv() 可能正在重用
代表它们的结构(就像您重用 FriendsMsg 结构一样)
Don't blame it on Java. What you show here doesn't say what the structure
or usage of UserID or Location are. fmsg.recv() is probably reusing the
structure that represents them (just as you are reusing the FriendsMsg structure)
很难说出您的代码有什么问题,因为您提供的代码片段不完整。我们没有太多关于您的数据结构(FriendMsg、ArrayList 朋友等)和从服务器接收的数据的信息。只是告诉你,错误不会来自Java或HashMap。您必须确保收到正确的数据。
It is very difficult to say what is wrong with your code because the code snippet that you gave is incomplete. We don't have much information about your data structure(FriendMsg,ArrayList friends, etc ) and the data received from the server. Just to tell you, the error will not come Java or the HashMap. You have to make sure that you are receiving the correct data.