File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

.equals()

 
sachin agashe
Ranch Hand
Posts: 42
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the following code the values assigned to the variable maxElement referenced by bothe the a and b objects is the same. Then why the result of the .equals method is false??
class MyClass{
static int maxElements;
MyClass(int maxElements){
this.maxElements = maxElements;
}
}
public class Q19{
public static void main(String[] args){
MyClass a = new MyClass(100);
MyClass b = new MyClass(100);
if(a.equals(b))
System.out.println("Objects have the samevalues");
else
System.out.println("Objects have different values");

System.out.println("a object: "+a.maxElements+" b object: "+b.maxElements);//this prints 100 100
}
}
 
akshaya bhatt
Greenhorn
Posts: 6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Go for String type of variables (inshort String class or wrapper class) and see the results.
Here u r using primitive data types which won't work as String class variables/objects
 
Ajith Kallambella
Sheriff
Posts: 5782
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
equals() is a method defined on the Object class. You can override it ( since all classes are subclasses of Object class ) to provide more meaningful comparison. However, when you don't override it, the default implementation of the method is called, which does nothing but plain reference comparison.
This means if not overridden, equals() returns true if the two objects being compared are one and the same( not the content, but the object itself ) and returns false if they are different( even if the content is the same ).
Now lets look at your code. Since MyClass doesn't override the equals method, the behaviour that you are seeing is the result of the method being called on the Object class. Hence it returns false.
Hope that helps,
Ajith
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic