这等于实现好吗?

时间:2014-04-17 01:17:58

标签: java equals

我有一个缓存实现,我实现了KeyObject

因此缓存为HashMap<KeyObject , List<SomeObjects>>

这个KeyObject类,假设它有2个变量a,b;

class KeyObject {
    MyObject a;
    AnotherMyObject b;

    KeyObject(MyObject a, AnotherMyObject b){
          this.a = prop1 ; this.b= prop2;
    }
}

没关系,我根据MyObject和AnotherMyObject的属性实现了equals方法..

说出这样的话

public boolean equals(Object keyObject){
    if(keyObject.isSomeType() && this.a.isSomeType(){
       return keyObject.a.equals(this.a)
    }
    else{
        return keyObject.a.equals(this.a) && keyObject.b.equals(this.b)
    }
}

上述平等实施是否是一种常见做法?

由于

2 个答案:

答案 0 :(得分:3)

三件事:

  1. 检查您要比较的对象是否为空。
  2. 使用instanceof确保其他对象的类型正确。
  3. 在测试相等性之前,键入另一个ObjectKeyObject
  4. 这样的事情:

    // Override annotation gives you bonus points :)
    @Override
    public boolean equals(Object other) {
        if (other == null)
            return false;
    
        if (!(other instanceof KeyObject))
            return false;
    
        KeyObject keyObject = (KeyObject) other;
    
        // I'm not exactly sure what this line is doing
        // but I assume it's part of your program.
        if(keyObject.isSomeType() && this.a.isSomeType()
            return keyObject.a.equals(this.a);
        else
            return keyObject.a.equals(this.a) && keyObject.b.equals(this.b);
    }
    

答案 1 :(得分:0)

我在谷歌搜索时发现了这个指南:Implementing equals

  
      
  • 对象字段,包括集合:use equals
  •   
  • 类型安全的枚举:使用equals或==(在这种情况下,它们相同,相同)
  •   
  • 可能为空的对象字段:同时使用==和等于
  •   
  • 数组字段:使用Arrays.equals
  •   
  • 除float或double之外的原始字段:use ==
  •   
  • float:使用Float.floatToIntBits转换为int,然后使用==
  •   
  • double:使用Double.doubleToLongBits转换为long,然后使用==
  •   

我认为这些指南几乎都是你需要的。

相关问题