EqualsBuilder vs own equals method

前端 未结 4 1881
小蘑菇
小蘑菇 2021-01-13 05:25

I just came across a code using EqualsBuilder() in equals method. Is there any advantage of using it instead of writing (or generating from eclipse

相关标签:
4条回答
  • 2021-01-13 05:30

    I don't see need for example. Equals builder will generate exactly same code for you so the only difference is that you have less code in a class.

    From my perspective it's better to write those methods (as you always have to override hashCode when you override equals)

    0 讨论(0)
  • 2021-01-13 05:32

    Using ANYTHING except for your own implementation in equals() is GUARANTEED to be "worse" if you can use ... say a strictly unique ID.

    If your ID is really unique you will most likely have the best, possible implementation with this, of course it needs to be polished quite a bit:

    @Override
    public boolean equals(Object other)
    {
       if(other instanceof MyClass)
       {
          MyClass obj = (MyClass)other;
          return obj.getID() == this.getID();
       }
       else
          return false;
    }
    

    Have a look at this, this and especially this

    0 讨论(0)
  • 2021-01-13 05:43

    There are a few ways to approach this.

    1. You can roll your own - that has the highest likelihood of getting something subtle wrong.

    2. You can have Eclipse generate your equals and hashCode methods for you - that leaves a lot of code in place, subject to inadvertent edits, and subject to failure to update when the class acquires a new field.

    3. You can use EqualsBuilder; it avoids the aforementioned problems.

    4. Best of all, at least in my experience, you can use lombok's EqualsAndHashCode annotation.

    0 讨论(0)
  • 2021-01-13 05:48

    Using an EqualsBuilder is not implicitly better or worse than writing your equals method from scratch. In other words, I don't consider using EqualsBuilder to be a best practice.

    A non-EqualsBuilder equals() method usually looks like this:

    public boolean equals(Object other) {
        boolean result;
    
        if(this == other)
            result = true;
        else
        if(other == null)
            result = false;
        else
        if(other instanceof MyClass) {
            MyClass o=(MyClass) other;
            result = Objects.equals(this.a, o.a)
                     && Objects.equals(this.b, o.b)
                     // ...
                     && Objects.equals(this.z, o.z);
        }
        else
            result = false;
    
        return result;
    }
    
    0 讨论(0)
提交回复
热议问题