Rahul Shilpakar wrote:if i have following lines in my code : -
Person p1 = new Person("monty", "jack");
Person p2 = new Person("monty", "jack");
p1 & p2 are not equal. WHY?
Integer i1 = new Integer(25);
Integer i2 = new Integer(25);
i1 & i2 are equal. WHY?
In case of Person class you need to override the equals(Person p) method and then check for the equality of the contents in that method. And you can read more about overriding hashCode and equals in thisthread.
Without seeing the code of the Person class, we honestly can't say if p1.equals(p2) will return true or false. If equals() is not overridden, then it will wihtout a doubt return false. However, if if it IS overridden, it would still depend on HOW it is overridden.
The Integer class, being part of the API, lets us check and see what exactly the equals() method does, and see that it will return true (in this case).
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
You should also say how it returns true and false; under some circumstances you can think you are creating two Integer objects and you are in fact creating one.Integers have special treatment, and small numbers (-128 to 127 or maybe a larger range) are cached, so try that code, then change 25 to 25000 and see whether you get different results.
This applies to Integers, and may apply to all eight wrapper classes, because they all say in the API for their valueOf methods that values may be cached.
permaculture is largely about replacing oil with people. And one tiny ad: