Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
First, we have to ask—what makes two Song references duplicates? They must be considered equal. Is it simply two references to the very same object, or is it two separate objects that both have the same title?
This brings up a key issue: reference equality vs. object equality.
If two objects foo and bar are equal, foo.equals(bar) must be true, and both foo and bar must return the same value from hashCode(). For a Set to treat two objects as duplicates, you must override the hashCode() and equals() methods inherited from class Object, so that you can make two different objects be viewed as equal.
Reference equality
Two references, one object on the heap.
Two references that refer to the same object on the heap are equal. Period. If you call the hashCode() method on both references, you’ll get the same result. If you don’t override the hashCode() method, the default behavior (remember, you inherited this from class Object) is that each object will get a unique number (most versions of Java assign a hashcode based on the object’s memory address on the heap, so no two objects will have the same hashcode).