开发者

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开发者_Go百科? But if I put (2,4) instead of (3,4) I will add a new pair of key/value to the HashMap. Right?


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.


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜