我们可以使用对象作为Java中hashmap的关键吗? [英] Can we use object as a key in hashmap in Java?

查看:89
本文介绍了我们可以使用对象作为Java中hashmap的关键吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在哈希映射中使用对象作为键。如果你使用一个对象作为键,你是否需要重写equals和hashcode方法?

HashMap 中使用不可变对象作为键。



因为:

>

如果它是可变的,那么 hashcode()值或 equals()条件可能会改变,并且您永远无法从 HashMap 中检索它。

更精确地说,$ c $> ,用于计算 equals() hashcode()的类字段应该是不可变的!



现在,假设您创建了自己的类:


  • 必须重写 equals()

  • 要将它用作任何基于Hash的数据结构中的键,您必须覆盖 hashcode()(再次牢记不变)



请记住,如果两个ob它们的 equals(),那么它们的 hashcode()也应该相同!


How to use an object as a key in a hashmap. If you use an object as key do you need to override equals and hashcode methods for that object?

解决方案

A simple thumb rule is to use immutable objects as keys in a HashMap.

because:

If it were mutable, then the hashcode() value or equals() condition might change, and you would never be able to retrieve it from your HashMap.

More precisely, class fields that are used to compute equals() and hashcode() should be immutable!

Now, suppose you create your own class:

  • To compare two objects of your class you will have to override equals()
  • To use it as a key in any Hash based Data structure you will have to override hashcode() (again, keeping immutability in mind)

Remember that if two objects are equal(), then their hashcode() should be equal as well!

这篇关于我们可以使用对象作为Java中hashmap的关键吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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