0

I have a class

public class A
{
    @Nonnull
    private final String m_a;

    @CheckForNull
    private final B m_b;

    @Nonnull
    private final List<C> m_c;

    @JsonCreator
    public A(
        @JsonProperty("a") @Nonnull final String a,
        @JsonProperty("b") @CheckForNull final B b,
        @JsonProperty("c") @Nonnull final List<C> c
    )
    {
        m_a = a;
        m_b = b;
        m_c = checkNotNull(c);
    }

    // getters ...
}

How would you recommend to compare if two A instances are equal?

I can use Jackson to serialize the JSON to a String (.writeValueAsString) and compare, but that is not cheap. Is it better if I override equals and hashcode and compare every field instead? What does it look like then?

MLEE
  • 17
  • 3
  • 8
    override `equals()` and `hashCode()` is usually the solution which makes more sense – fantaghirocco Dec 04 '20 at 16:19
  • 4
    Most IDE's can generate an `equals()` and `hashCode()` for you. – stdunbar Dec 04 '20 at 16:22
  • Or, also not cheap, but definitely cheaper than converting to JSON: `if (other == null) return false; A that = (A)other; return Objects.equals(Arrays.asList(a, b, c), Arrays.asList(that.a, that.b, that.c));` (_please don't do this_) – and always override `hashCode` if you provide a custom `equals` implementation – knittl Dec 04 '20 at 16:28
  • you'll have to make sure that `C` is also a comparable object when comparing the `c` lists – Bentaye Dec 04 '20 at 17:59

1 Answers1

1

Override equals() and hashCode() in class A and C, then you can compare two instances by A1.equals(A2)

And there are bunch of plugins that can generate them for you, example if you are using Intellij.

lennon310
  • 12,503
  • 11
  • 43
  • 61