Added efficient equals and isValid static methods.
This commit is contained in:
parent
d9feb90593
commit
b64f69cb00
@ -53,6 +53,26 @@ public final class Id<R> {
|
||||
return (int) value;
|
||||
}
|
||||
|
||||
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) {
|
||||
if (this == obj) return true;
|
||||
|
@ -38,6 +38,17 @@ public class IdTest extends TestCase {
|
||||
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 {
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user