java中hashCode和equals什么关系,hashCode到底怎么用的

Object类的hashCode的用法:(新手一定要忽略本节,否则会很惨) 
马 克-to-win:hashCode方法主要是Sun编写的一些数据结构比如Hashtable的hash算法中用到。因为hash很快,所以你往 Hashtable里放东西的时候,他先比一下,里面有没有现有的东西的hashCode和你一样,如果都不一样,证明是新的,就不再运行equals方 法了,直接放进Hashtable里了,很快。如果放的时候,Hashtable里面现有的某东西的hashCode和他一样,他再运行一下 equals,如不一样,则证明是新的,可以放入。equals也一样,证明确实是一样的,不让放入Hashtable。另外,Object的hashCode方法(Sun公司编的)是返回对象的内部地址。equals原始方法判断两个Object是否a==b,内存地址是否等(以下摘自sun的文档:As much as is reasonably practical, the hashCode method defined by class 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 JavaTM programming language.

最后,补充一点,Sun公司Object的equals方法文档上指明:for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true). Note that it is generally necessary tooverride the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes. 假如两个对象的equals返回值一样,hashcode返回值必须一样。但是反过来hashcode等,未必equals等,这就是刚才我们说先判断hashcode是否等,即使等,也要再运行equals,判断是否真的等。马克-to-win:从现实看,按照这逻辑编程,是效率最高,最合理的,本文这里的例子之所以没按照这条,只是为了说明本文所讲的问题。
例2.1.2.1(hashCode都不一样)---

import java.util.*;
class CompanyMark_to_win {
    private String name;
    CompanyMark_to_win(String name) {
        this.name = name;
    }
    public boolean equals(Object o) {
        System.out.println("equals被调用");
/*下句话,假如不是CompanyMark_to_win类型,马克-to-win:就返回假*/      
        if (!(o instanceof CompanyMark_to_win)) return false;
        CompanyMark_to_win c = (CompanyMark_to_win) o;//downcast,向下转型
        return name.equals(c.name);//这个equals是String的方法
    }
    public int hashCode() {  
        System.out.println("hashCode 被调用 "+super.hashCode());
        return super.hashCode();
    } 
}
public class Test {
    public static void main(String[] args) {
        CompanyMark_to_win c1 = new CompanyMark_to_win("Abc");

更多请见:https://blog.csdn.net/qq_44639795/article/details/103106468

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mark_to_win

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值