Home > Mobile >  AssertEquals tests in Java doesn't work for Pair objects
AssertEquals tests in Java doesn't work for Pair objects

Time:04-24

Does somebody know why this test fails? These are 2 identical objects with content inside, if I add the toString method after each Pair the test will pass. I tried to override the Equals method from the Object class but still nothing. Any help will be great, thanks

@Override
public int hashCode() {
   return Objects.hash(key, value);
}

@Override
public boolean equals(Object obj) {
    return super.equals(obj);
}

Pair Class Code
Error assertEquals
They are actual identical

CodePudding user response:

Your problem is that your override of equals doesn't do anything - it just calls the implementation that you overrode. In other words, it has no effect.

You need to override equals in a way that does the comparison that you need. In other words, your equals needs to

  • check that the Object being compared to is also a Pair,
  • call equals for the two key fields,
  • call equals for the two value fields.

If any of these conditions fail, your equals should return false.

CodePudding user response:

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Pair<?, ?> pair = (Pair<?, ?>) o;
    return key.equals(pair.key) && value.equals(pair.value);
}

This code resolved problem :)

  • Related