From de74482fe8dffcf6eed62438244cb08ddbc3f442 Mon Sep 17 00:00:00 2001 From: Inderjeet Singh Date: Mon, 12 Jul 2010 22:13:38 +0000 Subject: [PATCH] Implemented hashCode and equals for TypedKey to make it a value object. Asserted preconditions on constructor input. --- .../gson/webservice/definition/TypedKey.java | 29 +++++++++++++++++++ .../webservice/definition/TypedKeyTest.java | 23 +++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 wsdef/src/test/java/com/google/gson/webservice/definition/TypedKeyTest.java diff --git a/wsdef/src/main/java/com/google/gson/webservice/definition/TypedKey.java b/wsdef/src/main/java/com/google/gson/webservice/definition/TypedKey.java index 0556b55c..baa43a15 100644 --- a/wsdef/src/main/java/com/google/gson/webservice/definition/TypedKey.java +++ b/wsdef/src/main/java/com/google/gson/webservice/definition/TypedKey.java @@ -27,6 +27,9 @@ public class TypedKey { private final Class classOfT; public TypedKey(String name, Class classOfT) { + Preconditions.checkNotNull(name); + Preconditions.checkNotNull(classOfT); + this.name = name; this.classOfT = classOfT; } @@ -38,4 +41,30 @@ public class TypedKey { public Class getClassOfT() { return classOfT; } + + + @Override + public int hashCode() { + return name.hashCode() + classOfT.getCanonicalName().hashCode() >> 1; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + TypedKey other = (TypedKey) obj; + return name.equals(other.name) && classOfT.equals(other.classOfT); + } + + @Override + public String toString() { + return String.format("{name:%s, classOfT:%s}", name, classOfT); + } } diff --git a/wsdef/src/test/java/com/google/gson/webservice/definition/TypedKeyTest.java b/wsdef/src/test/java/com/google/gson/webservice/definition/TypedKeyTest.java new file mode 100644 index 00000000..309f3aa4 --- /dev/null +++ b/wsdef/src/test/java/com/google/gson/webservice/definition/TypedKeyTest.java @@ -0,0 +1,23 @@ +// Copyright 2010 Google Inc. All Rights Reserved. + +package com.google.gson.webservice.definition; + +import junit.framework.TestCase; + +/** + * Unit tests for {@link TypedKey} + * + * @author inder + */ +public class TypedKeyTest extends TestCase { + + public void testEqualsForSameName() { + assertEquals(new TypedKey("name", String.class), + new TypedKey(new String("name"), String.class)); + } + + public void testEqualsFailsForDifferentClasses() { + assertFalse(new TypedKey("name", Object.class).equals( + new TypedKey("name", String.class))); + } +}