0
votes

In the below key/value list "val3" is repeating for different keys. Which map suits best for such type of list.

I want "val3" should be stored only once with multiple keys pointing to it.

key1---->val1
key2---->val3
key3---->val3
key5---->val5
key6---->val3
key7---->val6
key8---->val3
key9---->val3

2
What exactly do you mean by "stored only once"?Jon Skeet
"val3" should not be repeated in the memory for each keyVasant
The complete object, or just the reference? That's what I was looking for with "exactly". I assume you understand how references and objects work in Java, and that a map would only ever contain a reference, not an actual object?Jon Skeet

2 Answers

2
votes

Any Map implementation will do. Every Java collection only holds references, not actual objects, so if you put the same object several times in a map, all the values will point to the same object. In other words changes made to val3 through key2 lookup will be reflected when looking up by any other key pointing to val3.

Consider simplified example:

VeryLarge v = new VeryLarge();
Map<Integer, VeryLarge> map = new HashMap<>();
map.put(1, v);
map.put(2, v);
map.put(3, v);

Single VeryLarge instance is referenced by all 1, 2 and 3 keys.

1
votes

As long as you ensure that you don't get values through clone operation or values aren't immutable objects (apart from String literals or Integer.valueOf()(values from -128 to 127 are caching and returned back from cache) which are exceptions), you'll end up with multiple keys pointing to the same concerned reference.

So you can use HashMap for instance, as @Tomasz Nurkiewicz has adviced.