Why is my Map broken?

Posted by Kirk on Stack Overflow See other posts from Stack Overflow or by Kirk
Published on 2010-05-24T02:16:51Z Indexed on 2010/05/24 2:20 UTC
Read the original article Hit count: 370

Filed under:
|
|
|
|

Scenario: Creating a server which has Room objects which contain User objects.

I want to store the rooms in a Map of some sort by Id (a string).

Desired Behavior:

When a user makes a request via the server, I should be able to look up the Room by id from the library and then add the user to the room, if that's what the request needs.

Currently I use the static function in my Library.java class where the Map is stored to retrieve Rooms:

public class Library {

  private static Hashtable<String, Rooms> myRooms = new Hashtable<String, Rooms>();

  public static addRoom(String s, Room r) {  
    myRooms.put(s, r);
  }

  public static Room getRoomById(String s) {
    return myRooms.get(s);
  }
}

In another class I'll do the equivalent of myRoom.addUser(user);

What I'm observing using Hashtable, is that no matter how many times I add a user to the Room returned by getRoomById, the user is not in the room later.

I thought that in Java, the object that was returned was essentially a reference to the data, the same object that was in the Hashtable with the same references; but, it isn't behaving like that. Is there a way to get this behavior? Maybe with a wrapper of some sort? Am I just using the wrong variant of map?

Help?

© Stack Overflow or respective owner

Related posts about java

Related posts about multithreading