Roman
Roman

Reputation: 131208

Does HashMap provide a one to one correspondence?

I found the following statement:

Map is an object that stores key/volume pairs. Given a key, you can find its value. Keys must be unique, but values may be duplicated.

For example I have just one key/value pair (3,4). And now I put a new pair (3,5). It will remove the old pair. Right? But if I put (2,4) instead of (3,4) I will add a new pair of key/value to the HashMap. Right?

Upvotes: 4

Views: 2378

Answers (4)

BalusC
BalusC

Reputation: 1109132

The answer to the question in your title is "No". The answer to the question in your message is "Yes". If you want a bidirectional map with unique keys and unique values as asked in your title (also called a key-key map), have a look at Guava BiMap.

Upvotes: 10

Vlad
Vlad

Reputation: 9481

You are correct. For each key there is only one value. But it is nothing to prevent multiple keys to have the same value.

Think of the HashMap like it is a box of drawers, each drawer can hold only one object and each drawer is marked with the key. So after you put an apple in drawer marked 1 you can't put an orange in there, unless you take out an apple from there first. However, nothing stops you from putting oranges in drawers 2 3 and 4.

Upvotes: 2

MattGrommes
MattGrommes

Reputation: 12354

Yes, the first number in the parentheses is the Key, you can think of it as the address. The second is the Value. The Key is unique, just like your home's address, but the Value can be anything.

Upvotes: 7

Jon Skeet
Jon Skeet

Reputation: 1502106

Yes, that's correct. If you want a one-to-one correspondence, use something like BiMap from Guava (or Google's Java Collections library).

Upvotes: 1

Related Questions