posted 12 years ago
Hi try the following you will understand how equals() work...
create another object as follows...
add it into the set
now compiling and running the code you will see this output...
s=[5-Purchase, 2-Finance, 3-Admin, 1-Accounts, 4-HR, 3-Admin]
now override equals() and hashcode() methods...
now compiling and running the code you will see this output...
s=[5-Purchase, 4-HR, 3-Admin, 2-Finance, 1-Accounts]
conclusion...
d3 will always refers to the same object whether you add it several times or not, the compiler will see the same object, this was achieved by this...
but every time you say and giving it a different reference, e.g d6, and Dept does not override equals(), then everytime it's a complete new object, which will never be equal to any other with different reference, until equals() is overriden.
Dept d3 = new Dept(3, "Admin");
Dept d6 = new Dept(3, "Admin");
d3 will always be equal to d3, but d3 will only be equal to d6 if equals() is overriden.
Hope this helps.