aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Equals Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Equals " Watch "Equals " New topic
Author

Equals

Saurabh Malhotra
Greenhorn

Joined: Jul 07, 2002
Posts: 6
why "object has different values" is dispalyed as output?

class MyClass
{
static int maxElements;
MyClass(int maxElements)
{
this.maxElements = maxElements;
}

}

public class Test
{
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 same values");
else
System.out.println("Objects have different values");
}
}
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
I think you have a typo, maxElements isn't static, is it?
Because MyClass hasn't overriden equals it inherits the method from the class Object. Object.equals() does a comparation with "==" . This only will return true if the variables compared point to the same object. In our example two objects are created, though the hold the same information they are different objects.
You must place within MyClass an overriding equals like:

For more, consult the API and the Sun's Java tutorial


SCJP2. Please Indent your code using UBB Code
Bharat Keskar
Greenhorn

Joined: Aug 26, 2002
Posts: 11
I think : the reason why the condition is false is that
you have to define your own .equals method in the top level class.
give it a try
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
The class MyClass has not defined a method boolean equals(Object).
So the one in the class Object is going to be used.
Variables a and b are referring to different objects, and therefore equals returns false
-Barry


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Barkat Mardhani
Ranch Hand

Joined: Aug 05, 2002
Posts: 787
Hi there:
It is worth mentioning that there is twist to the equal method. If equals method is comparing objects from classes other than String, All wraped primitive classes or string literals, then what is stated above holds true. Otherwise, the equal methods will compare the actual value of the objects (e.g. strings in case of String objects) and return true if both strings are identical. Here is program that I wrote for my understanding:
 
jQuery in Action, 2nd edition
 
subject: Equals