Added efficient equals and isValid static methods.
This commit is contained in:
parent
d9feb90593
commit
b64f69cb00
|
@ -53,7 +53,27 @@ public final class Id<R> {
|
||||||
return (int) value;
|
return (int) value;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
public static boolean isValid(Id<?> id) {
|
||||||
|
return id != null && id.value != NULL_VALUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A more efficient comparison method for ids that take into account of ids being nullable.
|
||||||
|
* Since the method is parameterized and both ids are of the same type, this method compares
|
||||||
|
* only id values, not their types. Note that this shortcut doesn't work if you pass raw ids
|
||||||
|
* to this method
|
||||||
|
*/
|
||||||
|
public static <T> boolean equals(/* @Nullable */ Id<T> id1, /* @Nullable */ Id<T> id2) {
|
||||||
|
if ((id1 == null && id2 != null) || (id1 != null && id2 == null)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (id1 == null && id2 == null) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return id1.value == id2.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
public boolean equals(Object obj) {
|
public boolean equals(Object obj) {
|
||||||
if (this == obj) return true;
|
if (this == obj) return true;
|
||||||
if (obj == null) return false;
|
if (obj == null) return false;
|
||||||
|
|
|
@ -38,6 +38,17 @@ public class IdTest extends TestCase {
|
||||||
assertTrue(Id.areEquivalentTypes(fooType, Id.class));
|
assertTrue(Id.areEquivalentTypes(fooType, Id.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void testStaticEquals() {
|
||||||
|
Id<Foo> id1 = Id.get(3L, Foo.class);
|
||||||
|
Id<Foo> id2 = Id.get(3L, Foo.class);
|
||||||
|
Id<Foo> id3 = Id.get(4L, Foo.class);
|
||||||
|
assertTrue(Id.equals(id1, id2));
|
||||||
|
assertFalse(Id.equals(null, id2));
|
||||||
|
assertFalse(Id.equals(id1, null));
|
||||||
|
assertTrue(Id.equals(null, null));
|
||||||
|
assertFalse(Id.equals(id1, id3));
|
||||||
|
}
|
||||||
|
|
||||||
private static class Foo {
|
private static class Foo {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue
Block a user