/** * Cities can have multiple zip codes. * For our simplified model, for the multiple case, we'll choose one (the first in our data source) * We'll use a 5-digit zip code */ public class Foo { private String name; private int id; //------------------------------------------------------- // Static Factory Constructor Methods (for convenience and clarity) /** Returns new Foo using static factory constructor method */ public static Foo fromNameId(String aName, int anId) { return new Foo(aName, anId); } //------------------------------------------------------- // Traditional Constructors /** Returns new Foo using parameters */ public Foo(String aName, int anId) { this.name = aName; this.id = anId; } /** Returns new Foo via copy constructor -- preserves the original */ public Foo(Foo source) { this(source.getName(), source.getId()); } //------------------------------------------------------- // Utility /** Returns nice string describing this object (typically one-line string) */ @Override public String toString() { return String.format("%s -- (%d)", this.getName(), this.getId()); } //------------------------------------------------------- // Accessing public String getName() { return this.name; } public int getId() { return this.id; } public void setName(String aName) { this.name = aName; } public void setId(int anId) { this.id = anId; } //------------------------------------------------------- // Equality /** Returns hash code */ @Override public int hashCode() { //note different technique for object (name) vs primitive (id) int hashCode = 7; hashCode = 31 * hashCode + (this.getName() != null ? this.getName().hashCode() : 0); hashCode = 31 * hashCode + this.getId(); return hashCode; } /** Returns true if this object equals parameter "o" */ @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Foo)) return false; Foo other = (Foo)o; //use safe equals for objects, use "==" for primitives return safeEquals(this.getName(), other.getName()) && (this.getId() == other.getId()); } //------------------------------------------------------- // Helper Methods (any methods we think of that make things simpler) /** Returns true if a is equal to be (considering nulls) */ private boolean safeEquals(Object a, Object b) { //If only one is nil, then false, use XOR*/ if (a==null ^ b==null) return false; //We now know both are null, or not null, check for condition #1 first*/ //If either is null, they both are if (a==null) return true; //Finally a simple equals return a.equals(b); } }