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

查看:36
本文介绍了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,如HashMapHashTableHashSet

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

hashCode() 收到的值用作桶号,用于存储集合/映射的元素.这个桶号是集合/映射中元素的地址.

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() 时,它将获取元素的哈希码,然后查找哈希码指向的存储桶.如果在同一个bucket中发现超过1个元素(多个对象可以有相同的hash码),则使用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天全站免登陆