• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

compare object

 
Stee Munche
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
I wanted to know if there exist already a method to compare objects. For example I have to compare two sub class objects. I want to know if they are of the same type(i.e an object student is not the same as an object address) and if they are it must return me true.
I hope someone will be able to help me.

Esroh
 
Norm Radder
Bartender
Posts: 1363
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to compare two objects and have the comparison look at your specifically specified fields, then you have to write the code to do that.

To know if an Object is of a specific type, use the instanceof operator.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It all depends on how the classes were written. Specifically, whether the classes themselves implement Comparable (so they can be compared to each other), or whether there exits a Comparator that will take instances of these classes as arguments.

If all you're concerned about is whether instances are "equal" and not concerned about any ordering relations if they're not, then the equals method should suffice, although this also requires that the method is overridden to give meaningful results. (And this would also limit the types of Collections that these instances could be placed in.)
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Mr. LLLLL,

Welcome to JavaRanch!

A bit of business: you may not have read our naming policy on the way in. It requires that you use a full, real (sounding) first and last name for your display name. Initials aren't enough. You can change your display name here. We take this policy rather seriously. Thanks for your cooperation.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you want to compare the objects or their types? These are two different ideas. To compare two objects, you typically need to implement Comparable or Comparator or override the equals() method depending on what kind of comparison you need.

If you want to determine the type of an object, you can use the instanceof operator. If you have two objects and whant to compare their types, you can use the getClass() method and compare the Class objects that are returned from each one. I think Class overrides equals. However, I highly doubt that this is what you want to do. I suspect the suggestions in my first paragraph are closer to what you really need to know.

Layne
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic