Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to equal same class objects  RSS feed

 
sandeep markala
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if i write a class i,e ClassA then i create two objects for that respective class, so here how can i equal those two objects.
 
Jeffry Kristianto Yanuar
Ranch Hand
Posts: 759
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
U can use equals method. equals method is inhereted from java.lang.Object. It will look like this:

ClassA classA1 = new ClassA(); //provide the constructor arguments
ClassA classA2 = new ClassA(); //provide the constructor arguments

if (classA1.equals(classA2)) {
System.out.println("Equals");
}
else {
System.out.println("Don't equals");
}

Of course you have to override this method to provide a kind of comparison to determine whether those 2 objects are equals.


I hope your problem are solved.



cheers


Jeffry Kristianto Yanuar
 
Rob Spoor
Sheriff
Posts: 21092
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By overriding the "public boolean equals(Object)" method.

How you do this is all up to you, but you should a) read the API of Object for some rules, and b) also override hashCode().

Now some checks you always want to perform:
- if the passed object is the same object, return true - this is for speed mostly
- if the passed object is null, return false
- if the passed object is of an incompatible class, return false

In code:

Instead of "getClass() != o.getClass()" you also often see code like "!getClass().isInstance(o)", or the more hardcoded version "!(o instanceof MyClass)".

While the latter two are perfect for final classes, they may lead to violation of one of the API rules for equals, if a subclass defines its own equals method using the same principle. If that's the case, then equals is no longer symmetric, since an instance of the subclass can be equal to an instance of your own class, but vice versa they will be unequal.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!