Mazzy
Mazzy

Reputation: 14179

setting hashcode and equals to create a set with unique object

I would create a Set exactly HashSet to contains only char.for example a,b,c,d,e,f,g... but these chars are not represented by the primitive type but I have an object

public FirstChar{

  private char c;

  public FirstChar(char c){

    this.c = c;

  }
}

Now i want to add the object FirstChar into a set but to avoid repeated elements I have to implement HashCode() and equals()

I know how to implement equals but how can i implement hashcode in the way I could have only one element in the set?

NB. Please don't say me to use Eclipse

Upvotes: 1

Views: 1879

Answers (2)

Vlad
Vlad

Reputation: 18633

In any case, from what I can tell, the hashCode method in the Character class simply returns the char as an int.

In your specific case, if you want the set to only contain the first FirstChar added to it, you can make all FirstChars equal to each other:

class FirstChar{
    private char c;
    public FirstChar(char c){
        this.c=c;
    }
    public String toString(){
        return String.valueOf(c);
    }
    public boolean equals(Object o){
        return o instanceof FirstChar;
    }
    public int hashCode(){        
        return 42;
    }
}

But unless you have a very good reason, this doesn't sound like a good idea.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499760

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>?

Upvotes: 3

Related Questions