Bookmark Topic Watch Topic
  • New Topic

.equals method for objects

 
Nitin Singla
Greenhorn
Posts: 15
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Report post to moderator
class testToString
{
public static void main(String args[])
{
Integer i=new Integer(4);
Integer y=new Integer(4);
checkToString cs = new checkToString(2);
checkToString c = new checkToString(2);
if( cs.equals(c))
System.out.println(" Both objects are equal");
else
System.out.println(" Unequal objects ");
if( i.equals(y))
System.out.println(" i,y - Both objects are equal");
else
System.out.println(" i,y - Unequal objects ");
}
}
class checkToString
{
int i;
checkToString()
{
i=10;
}
checkToString(int a)
{
this.i=a;
}
}



In my above class, i & y are giving true on using i.equals(y) and cs & c objects are giving false on using cs.equals(c). In both the cases we are not overriding equals() method. Can someone helps me here?
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Report post to moderator
As I stated in the other thread where you asked this question, what we do in our class doesn't matter here. It's Sring's and Integers equals() methods that are being called (as we can see clearly from the code), so it's what String and Integer do with equals() that matters. And both of those classes override equals(), as you can see in their javadocs.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49367
62
  • Mark post as helpful
  • send pies
  • Report post to moderator
Jeff Verdegan wrote:As I stated in the other thread where you asked this question, . . ..
For reasons stated here, it would cause confusion if you ask the same question twice.

And welcome to the Ranch
 
    Bookmark Topic Watch Topic
  • New Topic