There is need to compare two objects based on class they implement? When to compare using getClass()
and when getClass().getName()
? Is there any difference between this approaches to compare two Objects class types (names)?
public abstract class Monster { ... } public class MonsterTypeOne extends Monster { ... } public class MonsterTypeTwo extends Monster { ... } Monster monster = MonsterTypeOne(); Monster nextMonster = MonsterTypeTwo(); if(nextMonster.getClass().getName().equals(monster.getClass().getName()) )// #1 if(nextMonster.getClass().equals(monster.getClass()) )// #2
EDIT 1
What about: ?
nextMonster.getClass().equals(MonsterTypeOne.class)
In Java, the == operator compares that two references are identical or not. Whereas the equals() method compares two objects. Objects are equal when they have the same state (usually comparing variables). Objects are identical when they share the class identity.
This can occur through simple assignment, as shown in the following example. Value equality means that two objects contain the same value or values. For primitive value types such as int or bool, tests for value equality are straightforward.
Java String compareTo() MethodThe compareTo() method compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The method returns 0 if the string is equal to the other string.
Use class.equals()
:
if (nextMonster.getClass().equals(monster.getClass()))
or, because each class is like a singleton - there's only one instance of each Class per class loader, and most JVMs only have the one class loader - you can even use an identity comparison:
if (nextMonster.getClass() == monster.getClass())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With