Java中hashCode的用途是什么? [英] What is the use of hashCode in Java?

查看:155
本文介绍了Java中hashCode的用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中, obj.hashCode()返回一些值。这个哈希码在编程中有什么用?

In Java, obj.hashCode() returns some value. What is the use of this hash code in programming?

推荐答案

hashCode()用于 Hash 实现中的 bucketing ,如 HashMap HashTable HashSet 等。

hashCode() is used for bucketing in Hash implementations like HashMap, HashTable, HashSet, etc.

从<$ c $收到的值c> hashCode()用作桶号,用于存储集合/映射的元素。这个桶号是set / map中元素的地址

The value received from hashCode() is used as the bucket number for storing elements of the set/map. This bucket number is the address of the element inside the set/map.

当你执行 contains()时/ code>它将获取元素的哈希码,然后查找哈希码指向的桶。如果在同一个桶中找到多于1个元素(多个对象可以具有相同的哈希码),则它使用 equals()方法来评估对象是否相等,然后决定 contains()是真还是假,或者决定是否可以在集合中添加元素。

When you do contains() it will take the hash code of the element, then look for the bucket where hash code points to. If more than 1 element is found in the same bucket (multiple objects can have the same hash code), then it uses the equals() method to evaluate if the objects are equal, and then decide if contains() is true or false, or decide if element could be added in the set or not.

这篇关于Java中hashCode的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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