equals() 和 hashCode() 的区别

本文介绍了equals() 和 hashCode() 的区别的处理方法,对大家解决问题具有一定的参考价值

问题描述

我想要一个关于 equals() 、 "==" 和 hashCode() 的简要定义.如果我运行以下代码意味着输出将是true false 2420395 2420395".但我知道 equals() 方法比较字符串,=="比较引用.但是在输出中,hashCcode() 方法将两个字符串的参考号打印为相同,那么为什么=="返回false".

I want a brief definition about the equals() , "==" and hashCode(). If i run following code means the output will be "true false 2420395 2420395". But i had understand that equals() method compares the string and "==" compares the reference. But in output the hashCcode() method prints the reference number for both strings as same then why the "==" returns "false".

            String str = "Name";
    String str1 = new String("Name");

    if(str.equals(str1))
        System.out.println("true");
    else
        System.out.println("false");
    if(str==str1)
        System.out.println("true");
    else
        System.out.println("false");

    System.out.println(str.hashCode());
    System.out.println(str1.hashCode());
}

推荐答案

equals()hashCode() 方法被证明是非常重要的,当对象实现这些将两种方法添加到集合中.如果实施不当,可能会搞砸你的生活.

The equals() and hashCode() methods prove to be very important, when objects implementing these two methods are added to collections. If implemented incorrectly it might screwed up your life.

equals() :此方法检查作为参数传递给它的其他对象是否等于调用此方法的对象.如果您不了解合同,很容易错误地实现 equals() 方法.在覆盖此方法之前,需要牢记以下属性" -

equals() : This method checks if some other object passed to it as an argument is equal the object in which this method is invoked. It is easy to implement the equals() method incorrectly, if you do not understand the contract. Before overriding this method, following "properties" need to keep in mind -

  • 自反:o1.equals(o1) - 这意味着一个对象(例如 o1)应该等于它自己
  • 对称:o1.equals(o2) 当且仅 o2.equals(o1)
  • 传递:o1.equals(o2) &&o2.equals(o3) 意味着 o1.equals(o3) 也是如此
  • 一致:只要 o1 和 o2 未被修改,o1.equals(o2) 就返回相同的结果
  • null 比较:!o1.equals(null) - 这意味着任何可实例化的对象都不等于 null.因此,如果您将 null 作为参数传递给对象 o1,那么它应该返回 false.
  • 哈希码值:o1.equals(o2) 意味着 o1.hashCode() == o2.hashCode() .这是非常重要的.如果你定义了一个 equals() 方法,那么你也必须定义一个 hashCode() 方法.这也意味着,如果你有两个相等的对象,那么它们必须具有相同的 hashCode,但反之则不正确

来自java源代码

*
* @param   obj   the reference object with which to compare.
* @return  {@code true} if this object is the same as the obj
*          argument; {@code false} otherwise.
* @see     #hashCode()
* @see     java.util.HashMap
*/
public boolean equals(Object obj) {
   return (this == obj);

}

hashCode():此方法以整数形式返回 hashCode() 值,并支持基于散列的 java.util.Collection 类,如 Hashtable、HashMap、HashSet 等.如果类重写了equals()方法,它也必须实现hashCode()方法.在重写这个方法之前,你需要记住

hashCode(): This method returns a hashCode() value as an Integer and is supported for the benefit of hashing based java.util.Collection classes like Hashtable, HashMap, HashSet etc. If a class overrides the equals() method, it must implement the hashCode() method as well.Before overriding this method, you need to keep in mind

  • 在 Java 程序的执行过程中,当对同一个对象多次调用 hashCode() 方法时,该方法必须始终返回相同的结果.从程序的一次执行到同一程序的下一次执行,整数结果不必保持一致.
  • 如果根据 equals() 方法,两个对象相等,则在两个对象中调用 hashCode() 方法必须返回相同的整数结果.所以,如果一个字段没有在 equals() 中使用,那么它一定不能在 hashCode() 方法中使用.

  • Whenever hashCode() method is invoked on the same object more than once during an execution of a Java program, this method must consistently return the same result. The integer result need not remain consistent from one execution of the program to the next execution of the same program.
  • If two objects are equal as per the equals() method, then calling the hashCode() method in each of the two objects must return the same integer result. So, If a field is not used in equals(), then it must not be used in hashCode() method.

如果两个对象根据equals()方法不相等,则两个对象中的每一个都可以返回两个不同的整数结果或相同的整数结果(即如果2个对象具有相同的hashCode()结果并不意味着它们相等,但如果两个对象相等,则它们必须返回相同的 hashCode() 结果).

If two objects are unequal as per the equals() method, each of the two objects can return either two different integer results or same integer results (i.e. if 2 objects have the same hashCode() result does not mean that they are equal, but if two objects are equal then they must return the same hashCode() result).

根据java源代码java.lang.Object 定义的 hashCode 方法在合理可行的情况下确实为不同的对象返回不同的整数.(这通常通过将对象的内部地址转换为整数来实现)

As per java source code As much as is reasonably practical, the hashCode method defined by java.lang.Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer)

这篇关于equals() 和 hashCode() 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2

admin_action_{$_REQUEST[‘action’]}

do_action( "admin_action_{$_REQUEST[‘action’]}" )动作钩子::在发送“Action”请求变量时激发。Action Hook: Fires when an ‘action’ request variable is sent.目录锚点:#说明#源码说明(Description)钩子名称的动态部分$_REQUEST['action']引用从GET或POST请求派生的操作。源码(Source)更新版本源码位置使用被使用2.6.0 wp-admin/admin.php:...

日期:2020-09-02 17:44:16 浏览:1159

admin_footer-{$GLOBALS[‘hook_suffix’]}

do_action( "admin_footer-{$GLOBALS[‘hook_suffix’]}", string $hook_suffix )操作挂钩:在默认页脚脚本之后打印脚本或数据。Action Hook: Print scripts or data after the default footer scripts.目录锚点:#说明#参数#源码说明(Description)钩子名的动态部分,$GLOBALS['hook_suffix']引用当前页的全局钩子后缀。参数(Parameters)参数类...

日期:2020-09-02 17:44:20 浏览:1060

customize_save_{$this->id_data[‘base’]}

do_action( "customize_save_{$this->id_data[‘base’]}", WP_Customize_Setting $this )动作钩子::在调用WP_Customize_Setting::save()方法时激发。Action Hook: Fires when the WP_Customize_Setting::save() method is called.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分,$this->id_data...

日期:2020-08-15 15:47:24 浏览:800

customize_value_{$this->id_data[‘base’]}

apply_filters( "customize_value_{$this->id_data[‘base’]}", mixed $default )过滤器::过滤未作为主题模式或选项处理的自定义设置值。Filter Hook: Filter a Customize setting value not handled as a theme_mod or option.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分,$this->id_date['base'],指的是设置...

日期:2020-08-15 15:47:24 浏览:887

get_comment_author_url

过滤钩子:过滤评论作者的URL。Filter Hook: Filters the comment author’s URL.目录锚点:#源码源码(Source)更新版本源码位置使用被使用 wp-includes/comment-template.php:32610...

日期:2020-08-10 23:06:14 浏览:925

network_admin_edit_{$_GET[‘action’]}

do_action( "network_admin_edit_{$_GET[‘action’]}" )操作挂钩:启动请求的处理程序操作。Action Hook: Fires the requested handler action.目录锚点:#说明#源码说明(Description)钩子名称的动态部分$u GET['action']引用请求的操作的名称。源码(Source)更新版本源码位置使用被使用3.1.0 wp-admin/network/edit.php:3600...

日期:2020-08-02 09:56:09 浏览:873

network_sites_updated_message_{$_GET[‘updated’]}

apply_filters( "network_sites_updated_message_{$_GET[‘updated’]}", string $msg )筛选器挂钩:在网络管理中筛选特定的非默认站点更新消息。Filter Hook: Filters a specific, non-default site-updated message in the Network admin.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分$_GET['updated']引用了非默认的...

日期:2020-08-02 09:56:03 浏览:855

pre_wp_is_site_initialized

过滤器::过滤在访问数据库之前是否初始化站点的检查。Filter Hook: Filters the check for whether a site is initialized before the database is accessed.目录锚点:#源码源码(Source)更新版本源码位置使用被使用 wp-includes/ms-site.php:93910...

日期:2020-07-29 10:15:38 浏览:825

WordPress 的SEO 教学:如何在网站中加入关键字(Meta Keywords)与Meta 描述(Meta Description)?

你想在WordPress 中添加关键字和meta 描述吗?关键字和meta 描述使你能够提高网站的SEO。在本文中,我们将向你展示如何在WordPress 中正确添加关键字和meta 描述。为什么要在WordPress 中添加关键字和Meta 描述?关键字和说明让搜寻引擎更了解您的帖子和页面的内容。关键词是人们寻找您发布的内容时,可能会搜索的重要词语或片语。而Meta Description则是对你的页面和文章的简要描述。如果你想要了解更多关于中继标签的资讯,可以参考Google的说明。Meta 关键字和描...

日期:2020-10-03 21:18:25 浏览:1695

谷歌的SEO是什么

SEO (Search Engine Optimization)中文是搜寻引擎最佳化,意思近于「关键字自然排序」、「网站排名优化」。简言之,SEO是以搜索引擎(如Google、Bing)为曝光媒体的行销手法。例如搜寻「wordpress教学」,会看到本站的「WordPress教学:12个课程…」排行Google第一:关键字:wordpress教学、wordpress课程…若搜寻「网站架设」,则会看到另一个网页排名第1:关键字:网站架设、架站…以上两个网页,每月从搜寻引擎导入自然流量,达2万4千:每月「有机搜...

日期:2020-10-30 17:23:57 浏览:1298