mirror of
https://github.com/Snailclimb/JavaGuide
synced 2025-06-20 22:17:09 +08:00
hashcode方法讲解的完善
This commit is contained in:
parent
69c53d0b56
commit
2f61492874
@ -236,7 +236,27 @@ public class test1 {
|
|||||||
面试官可能会问你:“你重写过 hashcode 和 equals 么,为什么重写equals时必须重写hashCode方法?”
|
面试官可能会问你:“你重写过 hashcode 和 equals 么,为什么重写equals时必须重写hashCode方法?”
|
||||||
|
|
||||||
### hashCode()介绍
|
### hashCode()介绍
|
||||||
hashCode() 的作用是获取哈希码,也称为散列码;它实际上是返回一个int整数。这个哈希码的作用是确定该对象在哈希表中的索引位置。hashCode() 定义在JDK的Object.java中,这就意味着Java中的任何类都包含有hashCode() 函数。另外需要注意的是: Object 的 hashcode 方法是本地方法,也就是用 c 语言或 c++ 实现的,该方法直接返回对象的 内存地址。
|
hashCode() 的作用是获取哈希码,也称为散列码;它实际上是返回一个int整数。这个哈希码的作用是确定该对象在哈希表中的索引位置。hashCode() 定义在JDK的Object.java中,这就意味着Java中的任何类都包含有hashCode() 函数。另外需要注意的是: Object 的 hashcode 方法是本地方法,也就是用 c 语言或 c++ 实现的,该方法通常用来将对象的 内存地址 转换为整数之后返回。
|
||||||
|
|
||||||
|
```java
|
||||||
|
/**
|
||||||
|
* Returns a hash code value for the object. This method is
|
||||||
|
* supported for the benefit of hash tables such as those provided by
|
||||||
|
* {@link java.util.HashMap}.
|
||||||
|
* <p>
|
||||||
|
* As much as is reasonably practical, the hashCode method defined by
|
||||||
|
* class {@code Object} does return distinct integers for distinct
|
||||||
|
* objects. (This is typically implemented by converting the internal
|
||||||
|
* address of the object into an integer, but this implementation
|
||||||
|
* technique is not required by the
|
||||||
|
* Java™ programming language.)
|
||||||
|
*
|
||||||
|
* @return a hash code value for this object.
|
||||||
|
* @see java.lang.Object#equals(java.lang.Object)
|
||||||
|
* @see java.lang.System#identityHashCode
|
||||||
|
*/
|
||||||
|
public native int hashCode();
|
||||||
|
```
|
||||||
|
|
||||||
散列表存储的是键值对(key-value),它的特点是:能根据“键”快速的检索出对应的“值”。这其中就利用到了散列码!(可以快速找到所需要的对象)
|
散列表存储的是键值对(key-value),它的特点是:能根据“键”快速的检索出对应的“值”。这其中就利用到了散列码!(可以快速找到所需要的对象)
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user