Reputation: 1305
Is it a good programming practice to keep the same object in multiple collections?
Lets say i have a map, which contains eg.: 500+ elements,
Map<String,MyObject> map = new HashMap<>();
My application works with multiple connected clients, and i know that each client will almost always use only ±20 known and different elements from this map.
My question is if is it a good idea to create a map for each client which will hold these 20 elements if I want to save some iterations.
Upvotes: 2
Views: 1042
Reputation: 4199
Yes, it is a good idea, since it will take less time to get the needed objects from a map, if a map is smaller. As long as you are not cloning those objects, and not having duplicate objects in different maps
Upvotes: 1
Reputation: 31603
Sure it is. It can even be a way to reuse objects instead of creating a lot of new objects which holds identical data (you would call this a pool of objects or a fly weight pattern).
However, it belongs on the context and you must be sure who and how the objects can be changed. If client A changes an object, it will also be changed for client B. If this is what you have intended, it is perfectly ok.
Upvotes: 6