previous | start | next

Best Practice for Keys

Best Practices
  1. Make sure the equals method for the Key type tests for equality as you expect.
  2. If possible the Key type should be immutable
equals

Since searching for a key in a symbol table uses equality, problems occur if the equals method for the Key type is too strict.

Not every Java class overrides the equals method inherited from Object. So some classes use Object's equals method which IS too strict.

The equals method in Object is almost always too strict: x.equals(y) is true for Object's equals only if x and y reference the same object; that is, only if x == y.

Immutable Keys

If the Key type has methods that can change a key's state (i.e., Key type is NOT immutable) the key in some (key, value) pair in the symbol table can be changed to another key already in the symbol table. This would violate the rule that keys can't be duplicated.

If Key type is immutable, this can't occur.

See the code examples



previous | start | next