BlackBishop
BlackBishop

Reputation: 737

How are Hash Map values stored (in case the values are duplicates)?

Does a Java HashMap save duplicate values as unique or does it save them individually?

Let's imagine I have the following key-value pairs value:

A -> "a very long string...."
B -> "another very long string...."
C -> "the same very long string from A key.... (but not same string instance)"

Will it be saved as 3 keys and 3 values, or as 3 keys and 2 values (as value for A is exactly the same as value for C)

My concern is about sizing as the values I am going to save are quite big and make no sense duplicate them.

Upvotes: 3

Views: 376

Answers (4)

Andrew
Andrew

Reputation: 49626

It doesn't keep values, it holds references to values, so the problem boils down to the question "Are "a very long string...." and "the same very long string from A key...." the same object in memory?"

If they aren't compile-time constants and are obtained/constructed at runtime, they are different objects. String interning, along with String#intern, can help you here but has its limitations mentioned by @bratkartoffel.

What is Java String interning?
When should we use intern method of String on String literals
Performance penalty of String.intern()

Upvotes: 2

Eugene
Eugene

Reputation: 120868

But this does not concern HashMap, I mean it is not specific to it. Having a value as a String implies two other different things too - such as String interning or the fact that Strings are immutable. Also a HashMap does not copy the value (whatever that might mean), it only stores references to other objects - what you do with those Objects is entirely up to you. If you change an Object outside of the HashMap and then query that Map against that particular associated key, you will see the update.

Upvotes: 2

Eran
Eran

Reputation: 393856

A HashMap can contain duplicate values, so in your example there would be 3 keys and 3 values in the Map.

However, if you are concerned about large instances being stored multiple times as values in your Map, you should store references to the same instance.

For example:

String val = "a very long String............";
String val2 = "a second long String.........";
map.put(1,val);
map.put(2,val2);
map.put(3,val);

There are only two large String instances. The Map contains 3 references to those Strings (two references to the first String and one reference to the second String), but references occupy a small amount of storage.

Upvotes: 3

Niby
Niby

Reputation: 494

The Java HashMap does not allow duplicate keys, but it does allow duplicate values. So it would save them as 3 keys and 3 values.

In order for it to not save the value twice, you would have to check for it (for example by using the .containsValue() method).

Upvotes: 1

Related Questions