Hello Ron,
I checked out what you said and found out that
your statement is not only valid for the proper
function of the contains() method but for the
add() method, too.
It seems if you create your own class like "Employee" and want to store it properly in
a HashSet then you have to override hashCode and equals:
In the following programs I want to check out the effects of „equals()“ and hashCode() on a
HashSet.
The result is that if you create a Set with objects of a class of your own (like „Employee“
you have to override equals() and hashCode() in your class. Otherwise your HashSet will not
work properly for instance if you add() a new element into a HashSet then it shouldn’t accept
any duplicates. To find out whether a new element is already in the set it relies on the
hashCode() and the equals() method to find that out.
It first looks for elements with the same hashCode() as the element which should be added.
Therefore it has to call you overridden hashCode() method in class „Employee“.
If it finds an object in the set with the same hashCode as the added element then it calls the
overridden equals() method to check for „real equality“ as the same hashCode is not a 100%
ouarantee for object equality.
If the hashCode() and equals() method is not implemented in the class „Employee“
(like in Employee_Test3) then you can add duplicate employees.
Only if you override equals() properly like in „Employee_Test3a“ then you can ensure that
your HashSet will not contain duplicate „Employee“ entries.
C:\Java\EigeneJavaProgramme>
java Employee_Test3
[EmployeeNo. 1 Name: Markl, EmployeeNo. 1 Name: Markl, EmployeeNo. 2 Name: Meier]
C:\Java\EigeneJavaProgramme>java Employee_Test3a
[EmployeeNo. 2 Name: Meier, EmployeeNo. 1 Name: Markl]
[ November 17, 2002: Message edited by: Michael Ernest ]