// Supposing this class is going to function as a KEY -- it should be immutable! // (See numbered comments below that describe how we ensure this) public final class ImmutableSbPair { // 1) declare class as final (so it can't be extended) private final StringBuilder x; // 2) all instance vars should be private, so client has no direct access private final StringBuilder y; // 3) mutable instance variables should be marked "final" // so their values can only be assigned once public ImmutableSbPair(StringBuilder x, StringBuilder y) { this.x = new StringBuilder(x.toString()); // 4) initialize all instance vars via a this.y = new StringBuilder(y.toString()); // constructor using defensive (and deep) copies } // 5) don't provide any mutator methods (note, none of the methods below change x or y) public String toString() { return "(" + x + "," + y + ")"; } public int hashCode() { int h = 17; h = 31 * h + x.hashCode(); h = 31 * h + y.hashCode(); return h; } // 6) provide no accessor methods for mutable parts of the object -- if needed, return a deep copy instead public StringBuilder getX() { return new StringBuilder(x.toString()); } public StringBuilder getY() { return new StringBuilder(y.toString()); } }