why equals() method when we have == operator?
You can not overload the ==
operator, but you can override equals(Object)
if you want it to behave differently from the ==
operator, i.e. not compare references but actually compare the objects (e.g. using all or some of their fields).
Also, if you do override equals(Object)
, have a look at hashCode()
as well. These two methods need to be compatible (i.e. two objects which are equal according to equals(Object)
need to have the same hashCode()
), otherwise all kinds of strange errors will occur (e.g. when adding the objects to a set or map).
What is the difference between == and equals() in Java?
In general, the answer to your question is "yes", but...
.equals(...)
will only compare what it is written to compare, no more, no less.- If a class does not override the equals method, then it defaults to the
equals(Object o)
method of the closest parent class that has overridden this method. - If no parent classes have provided an override, then it defaults to the method from the ultimate parent class, Object, and so you're left with the
Object#equals(Object o)
method. Per the Object API this is the same as==
; that is, it returns true if and only if both variables refer to the same object, if their references are one and the same. Thus you will be testing for object equality and not functional equality. - Always remember to override
hashCode
if you overrideequals
so as not to "break the contract". As per the API, the result returned from thehashCode()
method for two objects must be the same if theirequals
methods show that they are equivalent. The converse is not necessarily true.
Difference between == operator and Equals() method in C#?
There are several things going on. Firstly, in this example:
string s1 = "a";
string s2 = "a";
Console.WriteLine(s1 == s2);
You claim that:
Both are different object reference.
That's not true due to string interning. s1
and s2
are references to the same object. The C# specification guarantees that - from section 2.4.4.5 of the C# 4 specification:
When two or more string literals that are equivalent according to the string equality operator (§7.10.7) appear in the same program, these string literals refer to the same string instance.
So in this particular case, you would still get "true" even if you printed object.ReferenceEquals(s1, s2)
, or if you made it use a true reference identity comparison with ==
:
object s1 = "a";
object s2 = "a";
Console.WriteLine(s1 == s2); // Still prints True due to string literal interning
However, even if these were references to separate objects, ==
is overloaded for string
. Overloading is a compile-time decision - the implementation to use depends on the compile-time types of the operands. So for example:
string a = new string('x', 1);
string b = new string('x', 1);
Console.WriteLine(a == b); // Uses string's implementation, prints True
object c = a;
object d = b;
Console.WriteLine(c == d); // Reference identity comparison, prints False
Compare that with object.Equals(object)
which is a virtual method. As it happens, String
overloads this method as well, but importantly it overrides it. So if we change our code to:
string a = new string('x', 1);
string b = new string('x', 1);
Console.WriteLine(a.Equals((object) b));
object c = a;
object d = b;
Console.WriteLine(c.Equals(d));
... then both method calls in the compiled code will simply be to object.Equals(object)
, but they'll still both print True because of polymorphism: the implementation in String
will be used.
Here's what a call to the overloaded method would look like:
string a = new string('x', 1);
string b = new string('x', 1);
Console.WriteLine(a.Equals(b)); // Calls string.Equals(string)
what is the difference between == operator and equals()? (with hashcode() ???)
the == operator determines if 2 references point to the same object.
So
Object o1 = new Object();
Object o2 = o1;
o1 == o2; //true
o2 = new Object();
o1 == o2 // false
the Object.equals() method is "how do I determine if 2 references to objects, that are not the same object, are equal?"
If two references point to the same object, both
o1 == o2
o1.equals(o2)
should be true.
But if o1 and o2 are not the same object, they still might be equal logically. For any given class, equals depends on the semantics behind the object. For example, consider a class where field1 and field2 are set by the user, but field3 is computed and has a random element to its computation. It might make sense to define equals in this case to only depend on field1 and field2, and not field3. Thats why equals is necessary.
Relation between equals() method and == operator
These requirements ensure that the equals
method will have the semantics that people expect for the concept of equivalence, and the logical/mathematical properties.
So, we expect equivalence to be transitive: if A equals B and B equals C, then A equals C. And we expect symmetry: if A equals B then B equals A. And we expect equality to be reflexive: A equals A.
Confusion about comparison by .Equals() vs. == operator and primitives vs. objects
In section 1 line 3
int a = 0;
short b = 0;
Console.WriteLine(a.Equals(b));
you call this overload of int
: bool Equals(int other)
, because b
(short) can be implicitly converted to int
so this overload is chosen. It returns true. In Section 3 line 3
int a = 0;
short b = 0;
object a1 = a;
object b1 = b;
Console.WriteLine(a1.Equals(b1)); //???
another overload of int
(not object
, because Equals
is virtual method) is called: bool Equals(object other)
. For it to return true other
should have exactly the same type (int
), but it's really short
so it returns false. Boxing is not relevant here, which you can verify with this:
int a = 0;
int c = 0;
object a1 = a;
object c1 = c;
// yes, different objects
Console.WriteLine(a1 == c1); // false
// still equal, because both are boxed ints
Console.WriteLine(a1.Equals(c1)); // true
As for understanding, I think documentation contains all relevant information. Just remember that:
Both
==
operator andEquals
method can be manually defined in class and so in theory can do anything. Your understanding relates only to "default" behavior.==
is not virtual in common sense, unlikeEquals
method. So when you doa1 == b1
-==
to be called in defined in compile time (based on types ofa1
andb1
), but when you calla1.Equals(b1)
- it is virtually dispatched so method to call is defined at runtime.
Is it necessary to override == and != operators when overriding the Equals method? (.NET)
See the guidelines for overriding Equals() and operator==.
Quote:
By default, the operator == tests for reference equality by determining whether two references indicate the same object. Therefore, reference types do not have to implement operator == in order to gain this functionality. When a type is immutable, that is, the data that is contained in the instance cannot be changed, overloading operator == to compare value equality instead of reference equality can be useful because, as immutable objects, they can be considered the same as long as they have the same value. It is not a good idea to override operator == in non-immutable types.
Basically:
If you want == and != to behave like Equals(..)
and !Equals(..)
you need to implement the operators. You typically do this only with immutable types.
What's the difference between == and .equals in Java?
Yes, ==
with objects is a reference comparison* (checks if the operands are references to the same object), while equals
is whatever the class involved defines it to mean (within the requirements documented for equals
). Some classes define equals
as being the same as ==
, including Java's arrays. (Because they don't override the default implementation from Object.equals
, which uses ==
.)
If you want to compare Java arrays based on the equality of their contents, you use Arrays.equals
instead.
Your experiment would have worked if you used a class that defined equals
in a useful way, you were just unlucky picking arrays. It's a bit tricky to find a class in the JVM to use for this experiment, because so many either don't implement equals
(like arrays) or could be confusing because there are several immutable classes which may reuse instances (although not if you explicitly use new
; but I don't want to go down a path of having you use new
with something you probably shouldn't, like String
; more on that here). I'm going to give up on picking a good example and use the slightly old class SimpleDateFormat
:
DateFormat a = new SimpleDateFormat("yyyy-MM-dd");
DateFormat b = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(a == b ? "== Same" : "== Different");
System.out.println(a.equals(b) ? "equals Same" : "equals Different");
That outputs
== Different
equals Same
because SimpleDateFormat
defines equals
to check that the other object is also a SimpleDateFormat
with the same formatting.
Live example
Re your comment on the question:
I have someone the answer points but I only get the == part, if .equals is checking the content, how come the code didnt print "same" for the second if
Because equals
doesn't, necessarily, check content. It only does if a class overrides the default Object.equals
(which just uses ==
) and implements a content check. Arrays don't. (One could argue that they should have, but they don't.) Other classes, like SimpleDateFormat
and String
and Integer
and HashMap
do.
In essence: ==
is always a reference comparison. equals
may or may not be a contents comparison, depending on what class you're using it on.
So for instance, say we have this class:
class Example1
{
private int content;
Example1(int content) {
this.content = content;
}
public static void main (String[] args) throws java.lang.Exception
{
Example1 a = new Example1(42);
Example1 b = new Example1(42);
System.out.println(a == b ? "== Same" : "== Different");
System.out.println(a.equals(b) ? "equals Same" : "equals Different");
}
}
Since that class doesn't override equals
, you'll get the same answer ("Different") for both ==
and equals
. Live Example.
But if we override equals
to define what it would mean for two instances to be equal (in this case: because they have the same content):
class Example2
{
private int content;
Example2(int content) {
this.content = content;
}
@Override
public boolean equals(Object obj) {
if (obj == null || !obj.getClass().equals(this.getClass())) {
return false;
}
Example2 other = (Example2)obj;
return this.content == other.content;
}
@Override
public int hashCode() {
return this.content;
}
public static void main (String[] args) throws java.lang.Exception
{
Example2 a = new Example2(42);
Example2 b = new Example2(42);
System.out.println(a == b ? "== Same" : "== Different");
System.out.println(a.equals(b) ? "equals Same" : "equals Different");
}
}
Now equals
says two instances with the same content are the same, because the class defines what that means. Live Example. (Also note that when overriding equals
, you must override hashCode
, which is why I've done so above.)
* More generally, ==
tests if the values of its operands are the same. The value in the case of reference types is an object reference, and two object reference values are only the same when they refer to the same object are are only different when they refer to different objects (or one of them is null
; not referring to an object at all).
Related Topics
What Is the Regex to Extract All the Emojis from a String
How to Split a Java String at Backslash
Getting the Class Name from a Static Method in Java
Allowing Java to Use an Untrusted Certificate for Ssl/Https Connection
How to Properly Match Varargs in Mockito
Get List of JSON Objects with Spring Resttemplate
Integer.Tostring(Int I) VS String.Valueof(Int I)
Move/Copy File Operations in Java
Accessing a Variable from Another Class
What Is the Purpose of Flush() in Java Streams
Sorting Java Objects Using Multiple Keys
How to Replace the Awt Eventqueue with Own Implementation
Date Format Mapping to JSON Jackson
Why Do I Get Java.Lang.Abstractmethoderror When Trying to Load a Blob in the Db
When and Why JPA Entities Should Implement the Serializable Interface