Added efficient equals and isValid static methods.

This commit is contained in:
Inderjeet Singh 2010-11-01 16:00:01 +00:00
parent d9feb90593
commit b64f69cb00
2 changed files with 32 additions and 1 deletions

View File

@ -53,7 +53,27 @@ public final class Id<R> {
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) {
if (this == obj) return true;
if (obj == null) return false;

View File

@ -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 {
}
}