我必须使用第三方库中没有equals
和hashCode
的类型.
在我的示例中,这将由包含一些数据的类Box
播放.
问题是,我的实现仍然没有考虑到唯一实例的基数.
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;
}
}