You must either define both equals and hashCode or none of them. In your code for two instances of x and y from EnglishWord x.equals(y) == true while x.hashCode() != y.hashCode() will happen. This is not legal if you expect your class to work with collection classes from java.util. See Object JavaDoc . To fix this, add something like this:
@Override public int hashCode() { return this.word.hashCode(); }
The equals method must have the signature "public boolean equals (Object other)" - your equals accepts an EnglishWord parameter, which causes your method to be ignored. Fix:
@Override public boolean equals(Object other) { if (other == null) return false; if (other.getClass() != this.getClass()) return false; final EnglishWord ow = (EnglishWord) other; return ow.word.equals(this.word); }
Generally, using the @Override annotation can help make your encoding more robust against this error, since a run-time error thus turns into a compile-time error.
Also, your Comparable interface Comparable should probably use generics.
source share