1

I have a custom class that looks like below:

public class customClass(){
    private int keyCode;
    private boolean up;
    private String toTrigger;

    public String getTrigger();
    public boolean up();
    public int keyCode();
}

Whats the best way for performance to have a list of unique values?

I was thinking of a HashSet but how would i make sure its only unique instances of my customClass?

What do i need to override? Equals and HashCode? will that make sure that my Hash Set of CustomClass only have unique instances?

Thanks

Lemex
  • 3,772
  • 14
  • 53
  • 87
  • This might help you: http://stackoverflow.com/a/27609/1068167 – span Mar 18 '13 at 13:45
  • Basically, yes: Overriding `equals` and `hashCode` is enough, but make sure to override them correctly, which is not easy. (see link from *span* above) – Sentry Mar 18 '13 at 13:46
  • Ahh thanks :) So in a hash set what does the hash set use to determine if its equal? Hash code or equals? – Lemex Mar 18 '13 at 13:47
  • question: you need the instance unique or the value of instance unique? you mentioned both in your question. e.g. `Dummy d1 =new Dummy("a"); and Dummy d2= new Dummy("a");` they could be equal, but they are different instances. Could d1 and d2 stay in your list/set? – Kent Mar 18 '13 at 13:50
  • possible duplicate of [Overriding equals and hashCode in Java](http://stackoverflow.com/questions/27581/overriding-equals-and-hashcode-in-java) – Lix Mar 18 '13 at 18:27

1 Answers1

2

If a.equals(b) is true then there hashcode() must also be same.

  • Override both .equals() and .hashCode() in your custom class.

    Use the same fields of your custom class to calculate hashCode which you used to check equality in .equals().

  • Yes it'll make sure that there are only unique instances of your customClass in hash-set. So go for it.

VishalDevgire
  • 4,232
  • 10
  • 33
  • 59