Java equals for a Class. Is == same as .equals

Java

Java Problem Overview


Can we do a == on a Class variable instead of equals and expect the same result?

For example:

Class clazz = xyz;

Case A:

if(clazz == Date.class) {
// do something
}

Case B:

if(Date.class.equals(clazz)) {
// do something
}

Are Case A and Case B functionally same?

Java Solutions


Solution 1 - Java

Class is final, so its equals() cannot be overridden. Its equals() method is inherited from Object which reads

public boolean equals(Object obj) {
    return (this == obj);
}

So yes, they are the same thing for a Class, or any type which doesn't override equals(Object)

To answer your second question, each ClassLoader can only load a class once and will always give you the same Class for a given fully qualified name.

Solution 2 - Java

Yes.

Take a look at the Class class description and note that it inherits equals from Object, for which the method reads:

"The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true)."

Solution 3 - Java

Yes, since the code for equals(...) for class is the following:

public boolean equals(Object obj) {
	return (this == obj);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRameshView Question on Stackoverflow
Solution 1 - JavaPeter LawreyView Answer on Stackoverflow
Solution 2 - JavacheekenView Answer on Stackoverflow
Solution 3 - JavaJérôme VerstryngeView Answer on Stackoverflow