From b64f69cb00a5f39cc7fe93b082ddbd2e2ca4087e Mon Sep 17 00:00:00 2001 From: Inderjeet Singh Date: Mon, 1 Nov 2010 16:00:01 +0000 Subject: [PATCH] Added efficient equals and isValid static methods. --- .../gson/webservice/definition/rest/Id.java | 22 ++++++++++++++++++- .../webservice/definition/rest/IdTest.java | 11 ++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/wsdef/src/main/java/com/google/gson/webservice/definition/rest/Id.java b/wsdef/src/main/java/com/google/gson/webservice/definition/rest/Id.java index 3b1cae01..801baf3a 100644 --- a/wsdef/src/main/java/com/google/gson/webservice/definition/rest/Id.java +++ b/wsdef/src/main/java/com/google/gson/webservice/definition/rest/Id.java @@ -53,7 +53,27 @@ public final class Id { 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 boolean equals(/* @Nullable */ Id id1, /* @Nullable */ Id 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; diff --git a/wsdef/src/test/java/com/google/gson/webservice/definition/rest/IdTest.java b/wsdef/src/test/java/com/google/gson/webservice/definition/rest/IdTest.java index 4c41a01a..1f9ddd38 100644 --- a/wsdef/src/test/java/com/google/gson/webservice/definition/rest/IdTest.java +++ b/wsdef/src/test/java/com/google/gson/webservice/definition/rest/IdTest.java @@ -38,6 +38,17 @@ public class IdTest extends TestCase { assertTrue(Id.areEquivalentTypes(fooType, Id.class)); } + public void testStaticEquals() { + Id id1 = Id.get(3L, Foo.class); + Id id2 = Id.get(3L, Foo.class); + Id 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 { } }