s_lavie
asked on
compare between type of two objects
I want to compare between type of two objects:
Which method is better and why?
class MyClass
{
boolean equals(Object obj)
{
return (obj instanceof MyClass);
}
//or:
boolean equals(Object obj)
{
return (obj.getClass().equals(thi s.getClass ()))
}
}
Which method is better and why?
class MyClass
{
boolean equals(Object obj)
{
return (obj instanceof MyClass);
}
//or:
boolean equals(Object obj)
{
return (obj.getClass().equals(thi
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
The former - it produces fewer instructions.
Hi,
Method to choose depends on what you want to achieve. Fist method will return true if obj's class is subclass of MyClass, while second checks for precise class equality.
I'm afraid there is no way to check for class equality using instanceof operator. But if you want comparison to return true for subclasses, than instanceof is a good choice.
You might want to consider another subclassing issue. If you make subclass of MyClass, what your equals() would mean? Would you like to rewrite equals() for each subclass? Or rewrite your first approach to reflection:
boolean equals(Object obj)
{
return getClass().isInstance(obj) ;
}
Or choose second approach?
Regards,
Igor Bazarny,
Brainbench MVP for Java 1
Method to choose depends on what you want to achieve. Fist method will return true if obj's class is subclass of MyClass, while second checks for precise class equality.
I'm afraid there is no way to check for class equality using instanceof operator. But if you want comparison to return true for subclasses, than instanceof is a good choice.
You might want to consider another subclassing issue. If you make subclass of MyClass, what your equals() would mean? Would you like to rewrite equals() for each subclass? Or rewrite your first approach to reflection:
boolean equals(Object obj)
{
return getClass().isInstance(obj)
}
Or choose second approach?
Regards,
Igor Bazarny,
Brainbench MVP for Java 1
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:
- points to jim_cakalic@idg
Please leave any comments here within the
next seven days.
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER !
girionis
Cleanup Volunteer
I will leave a recommendation in the Cleanup topic area that this question is:
- points to jim_cakalic@idg
Please leave any comments here within the
next seven days.
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER !
girionis
Cleanup Volunteer
OK. Thanks. :-)
Jim
Jim