Implemented hashCode and equals for TypedKey to make it a value object.

Asserted preconditions on constructor input.
This commit is contained in:
Inderjeet Singh 2010-07-12 22:13:38 +00:00
parent b2af57d288
commit de74482fe8
2 changed files with 52 additions and 0 deletions

View File

@ -27,6 +27,9 @@ public class TypedKey<T> {
private final Class<T> classOfT;
public TypedKey(String name, Class<T> classOfT) {
Preconditions.checkNotNull(name);
Preconditions.checkNotNull(classOfT);
this.name = name;
this.classOfT = classOfT;
}
@ -38,4 +41,30 @@ public class TypedKey<T> {
public Class<T> 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);
}
}

View File

@ -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<String>("name", String.class),
new TypedKey<String>(new String("name"), String.class));
}
public void testEqualsFailsForDifferentClasses() {
assertFalse(new TypedKey<Object>("name", Object.class).equals(
new TypedKey<String>("name", String.class)));
}
}