Paweł Szczur
Paweł Szczur

Reputation: 5542

Java efficient serializable many-to-one map

I'm having a data which is a many-to-one relation.

// My class with lot of data
class MyClass{}

Map<Integer, MyClass> idToClass = ...;
MyClass c = new MyClass();
idToClass.put(1, c);
idToClass.put(2, c);

The map is serialized and sent over the network. I'm looking for either work-around or implementation of map which considers duplicate values.

It's not only efficiency question, putting the same value in a map has a semantic meaning (it's necessary for my program to produce correct results).

Edit: I'm considering keeping all distinct values in an array and the mapping in a map Map<Integer,Integer>. I would then make two lookups, first for index and the other in array for a value.

Upvotes: 2

Views: 63

Answers (1)

GhostCat
GhostCat

Reputation: 140457

Two important things to consider:

a) if you are just concerned with serializing "too much" because of duplicated hash values ... you could prevent that by simply creating your a custom serialization code. Meaning: instead of directly serializing this map, you would instead serialize: all the values (once), and then the "actual" mapping in a more efficient way. Doing that allows your other code to go unchanged.

b) step back from your current design/implementation. Meaning: maybe it would make sense to abstract from using this simple map; and making this information about relationship-via-multiple-map-values more obvious internally. You know, if you are not dealing with a single map, but with a class that represents all that knowledge (similar in the way that I suggested above for "a)".

Obviously "a)" might be the "more local" change, but from 10000 miles away ... I am tempted to suggest you focus on "b)".

Upvotes: 1

Related Questions