java.lang.Class does not override the equals method from java.lang.Object, which is implemented like this:
public boolean equals(Object obj) {
return (this == obj);
}
So a == b is the same as a.equals(b) (except if a is null).
java.lang.Class does not override the equals method from java.lang.Object, which is implemented like this:
public boolean equals(Object obj) {
return (this == obj);
}
So a == b is the same as a.equals(b) (except if a is null).
I am not sure if this will work for your specific situation, but you could try Class.isAssignableFrom(Class).
KlassA.class.isAssignableFrom(klass)
Comparing Java objects with different member variables - Software Engineering Stack Exchange
java - Is it clean to place method for comparing 2 objects of same class into that class? - Software Engineering Stack Exchange
java - Comparing two classes by its types or class names - Stack Overflow
How to compare two Java objects?
Videos
You need to provide your own implementation of equals() in MyClass.
@Override
public boolean equals(Object other) {
if (!(other instanceof MyClass)) {
return false;
}
MyClass that = (MyClass) other;
// Custom equality check here.
return this.field1.equals(that.field1)
&& this.field2.equals(that.field2);
}
You should also override hashCode() if there's any chance of your objects being used in a hash table. A reasonable implementation would be to combine the hash codes of the object's fields with something like:
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 37 + this.field1.hashCode();
hashCode = hashCode * 37 + this.field2.hashCode();
return hashCode;
}
See this question for more details on implementing a hash function.
You need to Override equals and hashCode.
equals will compare the objects for equality according to the properties you need and hashCode is mandatory in order for your objects to be used correctly in Collections and Maps
The “different member variables” is irrelevant. It’s an implementation detail. What you need is a set of rules which of two people comes first.
You could for example sort by family name, then given name, then date of birth, and if these are all three equal, take the name of the school, university or company (which will be different member variables) and compare them as strings. If that is equal, you might have student and employee ids, and the student ids might be unique, and the employee ids might be unique, but student and employee ids might be the same. So you could sort then students first ordered by id, followed by employees sorted by id, if you might sort by if first if student and employee ids are comparable.
(University or school and employer might be the same, because universities are also employers).
Comparing objects with different fields sounds like bad polymorphic design, whether it's Java or any other OOP language:
- If your comparator needs to know the precise subtype of an object to do the comparison, you mess-up with the the open-closed principle, since for every new subclassing, you'd potentially need to modify the comparator to select the relevant fields.
- If your comparator needs uses reflexion to find on its own the relevant fields to compare, you indirectly mess up with the principle of encapsulation, since you create a hidden requirement that information to be compared must be in some predetermined field.
If you want to sort People properly in a clean polymorphic design:
- you need to rely either on a field, available for any kind of
People, includingStudent, or - you may call some function/transformation that provides a unique value (e.g. a string) that allows to sort any
People.PeopleandStudentmay then just use a different transformation that will be passed to the comparator; Or - you only sort among homogeneous subtypes.
The generally-accepted idiom for such methods in Java is based on the Java Object equals() method, which accepts a different object for comparison:
public boolean equals(Object obj)Indicates whether some other object is "equal to" this one.
Ergo:
public bool IsSameColorAs(car other) {
return this.color == other.color;
}
Usage:
bool IsSameColor = car1.IsSameColorAs(car2);
The Single Responsibility Principle says that a class contains the logic pertaining to that class.
My take is that colors define what "Same" means, so the logic to test if two colors are "the same" would be implemented in your color class/struct, or an extension method for the color.
For example:
car1.Color.IsSameAs(car2.Color);
That also allows you to determine if two colors are too close for your application's purposes to tell apart they would still be considered the "same".
In C# you can use Extension methods to add functions for a class or struct you did not create. Here is an example:
public static class Extensions
{
public static bool IsSameAs(this Color thisColor, Color otherColor)
{
return Math.Abs(thisColor.R - otherColor.R + thisColor.G - otherColor.G + thisColor.B - otherColor.B) < 2;
}
}
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())
Is there any difference between this approaches to compare two Objects class types (names)?
Yes. Two classes may have the same name if they are loaded by different ClassLoaders.
"The basics of Java class loaders" says
At its simplest, a class loader creates a flat name space of class bodies that are referenced by a string name.
"Eclipse - a tale of two VMs (and many classloaders)" says
That means it's possible to have two classes with the same name loaded into a VM at once, provided that they have two separate ClassLoaders
When to compare using
getClass()and whengetClass().getName()?
If you want to know whether two objects are of the same type you should use the equals method to compare the two classes -- the first option.
I can't imagine why you'd want to do this, but if you want to know whether two objects with different concrete types have types with the same fully qualified name, then you could use the second. If you don't understand "concrete types" and "fully qualified names" in the context of Java then you're not writing type analysis code for java so you don't want to.
Hi there, it's my first time learning Java and I'd love some assistance with comparing two Java objects. Here is a KenoBall class:
public class KenoBall {
private static int number;
private static String colour;
private static String ball;
public KenoBall(int number, String colour) {
this.number = number;
this.colour = colour;
this.ball = number + colour;
System.out.print(number + colour + "\n");
}
public boolean matches(KenoBall other) {
if (What goes in here?) {
System.out.println("Tru");
return true;
} else {
System.out.println("False");
return false;
}
}
}And in my main method:
public static void main(String[] args) {
KenoBall k1 = new KenoBall(1, "R");
KenoBall k2 = new KenoBall(1, "R");
KenoBall k3 = new KenoBall(4, "B");
k1.matches(k2);
}If anyone can point me in the right direction I'd really appreciate it! Basically I'm trying to see if k1 is equal to k2 (and it should).
Thank you!
If they're from the exact same class:
boolean result = object1.getClass().equals( object2.getClass());
Now if they are compatible classes (if one is of a descendent class to the other):
HashMap<String,Object> hashMap = new HashMap<String,Object>();
LinkedHashMap<String,Object> linkedHashMap = new LinkedHashMap<String,Object>();
boolean result = hashMap.getClass().isAssignableFrom( linkedHashMap.getClass() );
As LinkedHashMap is a subclass of HashMap this result variable will be true, so this might probably be better for you as it's going to find exact and subclass matches.
Also, you should avoid using ".class" on variables, as it might not give you the correct result, example:
Object someText = "text value";
System.out.println( someText.class.getName() ); //this will print java.lang.Object and not java.lang.String
When you're using ".class" you're acessing the variable static property and not the class of the object itself.
You're missing the getClass() method,
if (object1.getClass().equals(object2.getClass()))
{
// do something
}