0

我正在使用 java.util.HashMap 来关联联系人姓名和与联系人关联的电话号码列表,因此它的类型为String, List<String>. 但是,可以有多个键可以映射到同一个桶,就像在说 key1:<1234,5678> 存储在哈希映射的索引 2 中一样。我可以有另一个 key2 可以散列到同一个索引中。那么,key1:<1234,5678> 会被 key2:<7890,1456> 代替吗???或者它会被链接起来并且 key1 和 key2 都将存储在该索引中?

编辑:我试图理解这一点,下面的代码只返回新墨西哥州。现在在这种情况下,他们都得到相同的哈希码,所以这是正确的冲突吗?在那种情况下,不应该将两个值都链接起来吗?那么存储不应该像说哈希码是 2 那么在地图(或数组)中的索引 2 应该是 1-Mexico, 1-New mexico 正确吗?所以返回的值应该是 Mexico 和 New mexico ?为什么不在这里被锁住?

public static void main(String[] args)
    {
        Map<Integer,String> map = new HashMap<Integer,String>();
        map.put(1, "Mexico");
        map.put(1, "New Mexico");
        System.out.println(map.get(1));

    }
4

3 回答 3

3

I'm not totally sure I understand your question.

In a standard HashMap, if you put another value with the same key, it replaces the first one.

But you may use for example a MultiMap (from Apache commons) to store more than one value per key.

If your question is related to more than one key having the same index, this is handled by the implementation : the keys for are stored in linked lists (one for each bucket) and real comparisons (using equals) are done on get and put operations so that no collision can happen as long as equals returns false.

As with any collection related problem, the important thing to do if you intend to use your own class is to correctly implement the equals and hashcode methods (read this).

Regarding your question in edit :

This is a feature of HashMap that the first value with a given key is erased by the new one. So "Mexico" is removed from the HashMap when you add "New Mexico".

If you want to have more than one value for a given key, use a MultiMap (or simply use a HashMap<Integer, List<String>> but the put operation is a little more tedious).

于 2012-09-03T16:28:27.023 回答
2

This is a design that you ought to think through more carefully. It seems to me that you're using a Map and primitives - String is a primitive when you use it this way - as a poor approximation to an abstraction that would be better served by a real abstract data type of your own design.

For example, contact name String doesn't feel like a good abstraction to me. How many repeated names are there in a phone book? Once your solution grows beyond a non-trivial size you'll have collisions.

So where's the Contact class? Let it encapsulate the name String and List of associated phone numbers in a single object, with a well-written equals and hashCode. Give it a unique id private member; no collisions that way. People who use that class will instantly get a better understanding of what you're trying to accomplish.

于 2012-09-03T16:28:54.270 回答
0

不,当两个不同的键散列到相同的值时,键被链接起来,然后在操作期间,系统对实际键执行等于以定位正确的条目。

如果你创建了一个只为 hashCode() 返回 1 的退化类,HashMap 仍然可以按照规范工作,它只会执行得非常糟糕并变成一个简单的列表。

于 2012-09-03T16:38:17.970 回答