I have to use a type from a 3rd party library that does not have equals and hashCode.
In my example this will be played by the class Box which contains some data.
I have create a custom static method which compares to instances according to the specification. In the example if the data are the same.
The problem is that my implementation still does not take into account the cardinality of the unique instances.
import org.junit.jupiter.api.Test;
import java.util.Collection;
import java.util.Objects;
import java.util.function.BiPredicate;
import static org.assertj.core.util.Lists.newArrayList;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class CustomEqualsTest {
public static final BiPredicate<Box, Box> EQUALS = CustomEqualsTest::equals;
static boolean equals(Box b1, Box b2) {
if (b1 == b2) {
return true;
}
if (b1 != null && b2 != null) {
return Objects.equals(b1.data, b2.data);
}
return false;
}
static class Box {
Integer data;
private Box(Integer data) {
this.data = data;
}
static Box of(Integer data) {
return new Box(data);
}
// intentionally skip equals
// intentionally skip hashCode
}
@Test
void testCustomEquals() {
assertTrue(equals(
newArrayList(Box.of(1)),
newArrayList(Box.of(1)), EQUALS));
assertFalse(equals(
newArrayList(Box.of(1)),
newArrayList(), EQUALS));
assertFalse(equals(
newArrayList(Box.of(1)),
newArrayList((Box) null), EQUALS));
assertFalse(equals(
newArrayList(Box.of(1)),
newArrayList(Box.of(2)), EQUALS));
assertFalse(equals(
newArrayList(Box.of(1), Box.of(1)),
newArrayList(Box.of(1)), EQUALS));
// This fails:
assertFalse(
equals(
newArrayList(Box.of(1), Box.of(1), Box.of(2)),
newArrayList(Box.of(1), Box.of(2), Box.of(2)),
EQUALS));
}
static <T> boolean equals(Collection<T> collection1, Collection<T> collection2, BiPredicate<T, T> equals) {
if (collection1.size() != collection2.size()) {
return false;
}
for (T t1 : collection1) {
boolean match = false;
for (T t2 : collection2) {
if (equals.test(t1, t2)) {
match = true;
break;
}
}
if (!match) {
return false;
}
}
return true;
}
}