开发者

HashMap Values Becoming Invalid?

So, I wrote this function which gets a list of users and 开发者_JAVA技巧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;
    }


Probably your UserID is mutable, and changes in a way changing its hashCode and/or equals behavior. This way you blow the HashMap completely.


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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜