tags:

views:

115

answers:

4

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?

+5  A: 

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 Google Collections BiMap.

BalusC
A: 

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

Jon Skeet
+5  A: 

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.

MattGrommes
+2  A: 

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.

Vlad