equals()方法在Java中如何工作 [英] How does equals() method work in Java

查看:93
本文介绍了equals()方法在Java中如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

equals方法比较两个对象值是否相等.我的问题是它如何比较两个对象?如何判断两个对象是否相等?我想基于它比较两个对象的知识.我不包括hashCode方法.

The equals method compares whether two object values are equal or not. My question is how it compares the two objects? How can it tell the two objects are equal or not? I want to know based on what it compares the two objects. I am not including the hashCode method.

推荐答案

默认实现,即类java.lang.Object之一,仅测试对同一对象的引用:

The default implementation, the one of the class java.lang.Object, simply tests the references are to the same object :

150    public boolean equals(Object obj) {
151        return (this == obj);
152    }

Java规范:

在运行时,如果两个操作数的值均为=,则==的结果为true null或两者都引用相同的对象或数组;否则,结果 是错误的.

At run time, the result of == is true if the operand values are both null or both refer to the same object or array; otherwise, the result is false.

此默认行为通常在语义上不令人满意.例如,您不能使用==来测试大型Integer实例的相等性:

This default behavior isn't usually semantically satisfying. For example you can't test equality of big Integer instances using == :

Integer a = new Integer(1000);
Integer b = new Integer(1000);
System.out.println(a==b); // prints false

这就是为什么该方法被覆盖的原因:

That's why the method is overridden :

722     public boolean equals(Object obj) {
723         if (obj instanceof Integer) {
724             return value == ((Integer)obj).intValue();
725         }
726         return false;
727     }

启用此功能:

System.out.println(a.equals(b)); // prints true

基于标识字段(通常是所有字段)的相等性,覆盖默认行为的类应测试语义是否相等.

Classes overriding the default behavior should test for semantic equality, based on the equality of identifying fields (usually all of them).

您似乎已经知道,应该相应地覆盖hashCode方法.

As you seem to know, you should override the hashCode method accordingly.

这篇关于equals()方法在Java中如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆