使用HashMap与自定义键 [英] Using HashMap with custom key

查看:127
本文介绍了使用HashMap与自定义键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

快速问题:如果我想使用 HashMap 与自定义类作为键,必须我覆盖 hashCode 函数?

解决方案

从技术上讲,您不必重写hashCode方法,只要相等的对象具有相同的hashCode。



所以,如果你使用由Object定义的默认行为,那么equals只返回true,只有同一个实例,不必重写hashCode方法。



但是,如果不重写equals和hashCode方法,这意味着您必须确保始终使用相同的密钥实例。



例如:

  MyKey key1_1 = new的myKey( KEY1); 

myMap.put(key1_1,someValue); // OK

someValue = myMap.get(key1_1); //返回正确的值,因为使用了相同的密钥实例;

MyKey key1_2 = new MaKey(key1); //不同的键实例

someValue = myMap.get(key1_2); //返回null,因为key1_2具有与key1_1和key1_1.equals(key1_2)不同的hashCode == false



<在实践中,你通常只有一个密钥实例,所以在技术上你不必重写equals和hashCode方法。



但最好的做法是覆盖对于用作键的类的equals和hashCode方法,因为有时候你或另一个开发人员可能会忘记使用相同的实例,这可能导致难以跟踪问题。


$ b $请注意:即使您重写了equals和hashCode方法,您也必须确保不以更改equals或hashCode方法结果的方式更改密钥对象,否则映射将找不到你的价值了。这就是为什么建议使用不可变对象作为键,如果可能的话。


Quick Question: If I want to use HashMap with a custom class as the key, must I override the hashCode function? How will it work if I do not override that function?

解决方案

Technically, you don't have to override the hashCode method as long as equal objects have the same hashCode.

So, if you use the default behaviour defined by Object, where equals only returns true only for the same instance, then you don't have to override the hashCode method.

But if you don't override the equals and the hashCode methods, it means you have to make sure you're always using the same key instance.

E.g.:

MyKey key1_1 = new MyKey("key1");

myMap.put(key1_1,someValue); // OK

someValue = myMap.get(key1_1); // returns the correct value, since the same key instance has been used;

MyKey key1_2  = new MaKey("key1"); // different key instance

someValue = myMap.get(key1_2); // returns null, because key1_2 has a different hashCode than key1_1 and key1_1.equals(key1_2) == false

In practice you often have only one instance of the key, so technically you don't have to override the equals and hashCode methods.

But it's best practice to override the equals and hashCode methods for classes used as keys anyway, because sometime later you or another developer might forget that the same instance has to be used, which can lead to hard to track issues.

And note: even if you override the equals and hashCode methods, you must make sure you don't change the key object in a way that would change the result of the equals or the hashCode methods, otherwise the map won't find your value anymore. That's why it's recommended to use immutable objects as keys if possible.

这篇关于使用HashMap与自定义键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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