zoukankan      html  css  js  c++  java
  • equals方法的编写建议

    • 1.显示参数命名为 otherObject ,稍后需要将其转换成另一个叫做 other 的变量。
    • 2.检测 thisotherObject 是否引用同一个对象:
    //这条语句只是一个优化。计算这个等式比一个一个地比较类中的域所付出的代价要小的多。
    if (this == otherObject) return true;
    
    • 3.检测otherObject是否为null,如果为null,则返回false
    • 4.比较thisotherObject 是否属于同一个类:
      如果equals的语义在每个子类中有所改变,就用getClass检测; 如果所有子类都有统一的语义,就用instanceof检测:
    //getClass
    if(getClass != otherObject.getClass())
    	return false;
    
    //instanceof
    if(!(otherObject instanceof ClassName))
    	return false;
    
    • 5.将otherObject转换成相应的类的类型变量:ClassName other = (ClassName)otherObject;
    • 6.现在开始对所有需要比较的域进行比较了。使用==比较基本类型域,使用equals比较对象域。如果所有的域都匹配,就返回ture,否则返回false
    return field1 == other.field1
    	&& Objects.equals(field2,other.field2)
    	&&···
    

    如果在子类中重新定义equals,就要在其中包含调用super.equals(other);

  • 相关阅读:
    js监听input输入框值的实时变化实例
    VUE生命周期函数
    每日记载内容总结43
    每日记载内容总结42
    1年后
    svg + d3
    python , angular js 学习记录【3】
    python , angular js 学习记录【2】
    python , angular js 学习记录【1】
    Python入门(二)
  • 原文地址:https://www.cnblogs.com/LittleTreasureBox/p/8759839.html
Copyright © 2011-2022 走看看