我们能否将嵌套地图作为其他地图中的键? [英] can we have a nested map as key within other map?

查看:68
本文介绍了我们能否将嵌套地图作为其他地图中的键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始用Java实现数据结构,想知道我们是否会遇到这样的情况。

I have just started implementing data structures in Java and was wondering can we have a situation like this.

Map<HashMap<String,String>,String> map = new HashMap<HashMap<String,String>,String>(); 

如果是,请举一个小例子。

And if yes ,, please give a small example.

如果找不到相关的问题,请在注释中提及

If you don't found question relevant ,, please mention in comments,

推荐答案

可以这样做,但是在大多数情况下您不应该这样做。

You can do this, but you should not do so in most cases.

映射的键必须是常量,并且必须设置其equals和hashcode给出正确的行为。如果在将密钥添加到地图后修改了密钥,则会使地图无效。

The key to a map needs to be constant and its equals and hashcode need to be set up to give the correct behavior. If you modify a key after adding it into the map then you invalidate the map.

可以修改HashMap,因此不应将其用作密钥。

A HashMap can be modified so should not be used as a key.

要解释为什么更改它是一个问题,您需要了解哈希图如何工作。这非常简化,但可以说您有一个包含两个存储桶的 HashMap H 。让我们称它们为B0和B1。

To explain why changing it is a problem you need to know how hashmaps work. This is very simplified but lets say you have a HashMap H containing two buckets. Lets call them B0 and B1.

无论何时将 Object 添加到 HashMap 会查看对象 hashCode 。如果最后一位为0,则它​​将进入B0;如果最后一位为1,则它将进入B1。

Whenever you add an Object to the HashMap it looks at that objects hashCode. If the final bit is 0 then it goes in B0, if it is 1 then it goes in B1.

现在,当查找对象时,它会看到 hashCode 并立即转到正确的存储桶,然后只需搜索该存储桶中的对象以找到所需的对象。

Now when looking up an object it looks at the hashCode and immediately goes to the right bucket, it then only needs to search the objects in that bucket to find the object it needs.

使用多于2个的存储桶,可以将每个存储桶中的项目数减少2、4、8或更多次,从而减少需要检查的对象数。

By using more buckets than just 2 you can reduce the number of items in each bucket by 2, 4, 8 or more times and hence reduce the number of objects you need to check.

但是,可以说您在地图上放置了一个对象,该对象被添加到B0中。然后,您更改对象,并且hashCode更改,因此最后一位现在为1。

However lets say you put an object in the map and it gets added to B0. You then change the object and the hashCode changes so the last bit is now 1.

如果执行 map.contains(obj)您将得到错误的结果,因为它将查看hashCode,直接跳至B1并仅扫描该对象。但是该对象被放置在B0中,因为这是hashCode插入时的样子。

if you do map.contains(obj) you will get the result false because it will look at the hashCode, jump straight to B1 and only scan that for the object. But the object was placed in B0 because that is what the hashCode had at the time it was inserted.

这就是为什么hashCode对于用作对象的任何对象必须保持恒定的原因HashMap中的一个键,否则您可以丢失这些键。

This is why the hashCode must be constant for any object being used as a key in a HashMap, as otherwise you can "lose" these keys.

这篇关于我们能否将嵌套地图作为其他地图中的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆