What's REALLY going on in that HashSet.contains() method
posted by Ted on
We all know that contains() is a handy way to check for the presence of an item in a HashSet. The java docs state: "Returns true if this collection contains the specified element. More formally, returns true if and only if this collection contains at least one element e such that (o==null ? e==null : o.equals(e))." So, you just need to override equals() the way you want, and everything's hunky-dory, right? Wrong!
You also need to override hashCode(), because HashSet first compares hashCode(), and then equals(). In other words, two objects which are equal() but have different hashCode()s will never match. Therefore, contains() never returns true.