码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-09-24 16:41:42      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:ash   obj   text   must   ever   dde   lang   general   用法   

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 to override 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;
    }
。。。。。。。。。。。。。。。。。
详情请进:http://www.mark-to-win.com/index.html?content=JavaBeginner/javaUrl.html&chapter=JavaBeginner/JavaBeginner3_web.html#hashCode

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

标签:ash   obj   text   must   ever   dde   lang   general   用法   

原文地址:https://www.cnblogs.com/mark-to-win/p/9695425.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!