posted 15 years ago
Hi Preetha,
Replacing the code with
Object obj = n2;
if(n1.equals(obj))s+="1";
calls the Object class equals(), which just does a direct compare(==).
So, 1 is not printed in this case.
The reason it shows set.size() as 2 is because both the references do not refer to the same object, as(n1!=n2).
Try this out(assigns n1 to obj, so both refer to the same object):
Object obj = n1;
if(n1.equals(obj))s+="1"; //calls Object class equals()
if(n1==n2)s+="2";
Set<Nearly> set = new HashSet<Nearly>();
set.add(n1);
set.add((Nearly)obj); //trying to add duplicate
System.out.println(s + " " + set.size());
Now, set.size() will print 1.