EDIT: I've just read your comment that you only want one letter in the entire set - which sounds like a very odd requirement, but it's basically fulfilled by something like:
public final class FirstChar {
private final char c;
public FirstChar(char c) {
this.c = c;
}
@Override public int hashCode() {
return 0;
}
@Override public boolean equals(Object other) {
return other instanceof FirstChar;
}
}
In other words, every instance of FirstChar
is deemed equal to every other instance, and they all have the same hash code. As I say, this is really strange... is it definitely what you want?
Original answer
Implementing hashCode()
for a value which only logically has a single character is easy:
@Override
public int hashCode() {
return c; // Use implicit conversion to int
}
Check against the contract of Object.hashCode
and you'll find this works fine - assuming your equals
method basically just compares values of c
. (It's not clear what you meant when you wrote "in the way I could have only one element in the set" - I assume you mean only one element per distinct character.)
However, I'm confused as to what value your FirstChar
class provides over just using java.lang.Character
. Is there any reason you can't just use a Set<Character>
?