HashMap值变得无效?

时间:2011-04-19 22:34:28

标签: java networking hashmap

所以,我编写了这个函数,它获取用户及其位置列表(它是一个手机应用程序),它将正确的值粘贴到hashmap(ret.put(...))中,但一旦函数返回,地图中的所有值都设置为错误的UserID为0和Location 0,0。在我看来,Java正在删除fmsg,然后删除我放置在地图中的UserID和Location。你们觉得怎么样?

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;
    }

3 个答案:

答案 0 :(得分:3)

可能你的UserID是可变的,并且改变了hashCode和/或等于行为的方式。这样就可以完全打击HashMap

答案 1 :(得分:1)

不要责怪Java。你在这里展示的不是什么结构 或使用UserID或Location。 fmsg.recv()可能正在重用 表示它们的结构(正如您重用FriendsMsg结构一样)

答案 2 :(得分:0)

很难说您的代码有什么问题,因为您提供的代码段不完整。我们没有太多关于您的数据结构(FriendMsg,ArrayList friends等)以及从服务器收到的数据的信息。只是告诉你,错误不会来自Java或HashMap。您必须确保收到正确的数据。