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?
It’s very peculiar that you declare
myRoomsasHashtable<String, Rooms>(pluralRooms), but youputa singularRoom rinaddRoom.Are you trying to do some sort of multimap, where a key can map to a multiple values? If so, then either us the Guava implementation, or implement your own as a
Map<K,Set<V>>(map a key to a set of values).I’m not sure if this your fundamental issue, though.
It is correct that the returned value by
getshould be the same object, as defined by reference equality, as the one used input.The above is expected behavior.
Sometimes people have trouble with a
Mapbecause their key objects do not implementhashCodeandequalscontract properly, but if you’re usingStringas keys, this should not be an issue.By the way,
Hashtablehas a newer, sexier cousin inHashMap. I noticed themultithreadingtag in the question, so if you actually need thesynchronizedfeature, you can useCollections.synchronizedMapIn either case, whether you use a
HashMapor aHashtable, you want declaremyRoomssimply as aMap(see Effective Java 2nd Edition, Item 52: Refer to objects by their interfaces).Related questions