Link to home
Start Free TrialLog in
Avatar of haneef_nb
haneef_nb

asked on

how to compare two user defined objects in java?

Hi,

Please explain, how to compare two user defined objects in java, Kindly explain this with an example, because i have reffered so many articles, but still confusing.

Please do need full.

Thanks....
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

You use either a Comparator or make the object implement Comparable

http://lkamal.blogspot.com/2008/07/java-sorting-comparator-vs-comparable.html
Avatar of haneef_nb
haneef_nb

ASKER

suppose we have Employee object, if the empId is same, then we should not allow that object to add in collection....
Yes. All you'd need for that is to use a Set. Return the empId as the value of hashCode and implements Employee.equals based on empId. Simple
ASKER CERTIFIED SOLUTION
Avatar of a_b
a_b

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
> if the empId is same, then we should not allow that object to add in collection....

you need to first check if the object is in the collection.
The actual comparison is done with the equals() method which you need to overrride as a_b has shown above. In that method you define when two objects are considered to be equal
Thanks..