《effective java》-how to override the equals method

本文探讨了在Java中何时应该覆盖Object类的equals()方法,并详细阐述了覆盖equals()方法时应遵循的四个原则:自反性、对称性、传递性和一致性。通过示例代码展示了如何正确实现equals()方法,以及不正确覆盖可能带来的问题。同时,文章提醒在覆盖equals()方法前要确保满足特定的逻辑相等概念,并在完成后检查是否符合规范。

it looks sample to override the euqals mathod.however numerous override way will lead to wrong.and bring about terrible consequence,as we know,it is easiest that do not override the equals method to avoid those poblem.under the circumstance.object's every class only equals itself,if satisfy one of the following condition.this is the desird result:

  1. each instance of the class is uniqueness.for example as thread.Object provide euqals method is the right action for those class
  2. be indifferent to class have provided "logtical equality" test function.
  3. super class have overrided equals.it is also appropriate for subclass that extends from supclass's equals action.such as map extends abstractMap.
  4. class is private or package is private.it can affirm that its equals method will never called.

So.when we should override the Object.equals()?if class has its specific "logtical euqals" concept.and class has not been override the equals method to implement expect action.

during override the equals method.we must follow the following rules.

  1. reflexive.for every non-null reference value x.   x.euqals(x) must return true.
  2. symmetrice.for every non-null reference value x and y   x.euqals(y) must retrun same result with y.equals(x) 
  3. transitive.for every non-null reference value x、y、z.base on symmetrice.such as x.equals(y) and y.equals(z).therefore z.equals(x)
  4. consistent.for every non-null value x and y.so long as there value do not alter.it will return same return value with different time.

for any non-null reference value x. x.equals(null) must return false.

package EffectiveJava;

/**
 * @author 韦海涛
 * @version 1.0
 * @date 3/31/2021 1:05 AM
 */
public class No5Equals {
    static class Example{
        private int a;
        public Example(int i){
            this.a = i;
        }
        @Override
        public boolean equals(Object obj) {
            if(obj == this){//满足自反性
                return true;
            }else if(!(obj instanceof Example)){
                return false;
            }
            Example temp = (Example)obj;
            if(temp.a==this.a){
                return true;
            }else{
                return false;
            }
        }
    }

    public static void main(String[] args) {
        Example example1 = new Example(1);
        Object object=null;
        Example example2 = null;
        Example example3 = new Example(2);
        Example example4 = new Example(1);

        System.out.println(example1.equals(object));
        System.out.println(example1.equals(example2));
        System.out.println(example1.equals(example3));
        System.out.println(example1.equals(example4));
    }
}

integrate all of these requirements,we can draw serveral conclusions.

  1. using == operation symbol to check "parameter instanceof the class's reference".if true,then return true,although it will expensive operation.
  2. using instanceof operation symbol  "parameter is the true type"
  3. base on the instanceof test and transform right type
  4. for every key significant areain this class.check whether the area match the area of parameter
  5. when you have comleted the equals method ,ask yourself that the equals method hava accord with above rule.
Java 类中重写 `equals` 方法,需要遵循以下几个原则: 1. **自反性**:对于任何非空引用值 `x`,`x.equals(x)` 应该返回 `true`。 2. **对称性**:对于任何非空引用值 `x` 和 `y`,当且仅当 `y.equals(x)` 返回 `true` 时,`x.equals(y)` 才应该返回 `true`。 3. **传递性**:对于任何非空引用值 `x`、`y` 和 `z`,如果 `x.equals(y)` 返回 `true`,并且 `y.equals(z)` 返回 `true`,那么 `x.equals(z)` 也应该返回 `true`。 4. **一致性**:对于任何非空引用值 `x` 和 `y`,多次调用 `x.equals(y)` 应该始终返回相同的结果,前提是在比较期间没有修改对象的状态。 5. **非空性**:对于任何非空引用值 `x`,`x.equals(null)` 应该返回 `false`。 以下是一个重写 `equals` 方法的示例: ```java class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } @Override public boolean equals(Object obj) { // 检查是否为同一个引用 if (this == obj) { return true; } // 检查是否为 null if (obj == null) { return false; } // 检查是否为同一类型 if (getClass() != obj.getClass()) { return false; } // 转换为 Person 类型 Person other = (Person) obj; // 比较属性 if (age != other.age) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; } } ``` 在上述示例中,`Person` 类重写了 `equals` 方法,通过比较 `name` 和 `age` 属性来判断两个 `Person` 对象是否相等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值