== or .Equals()

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 override equals so as not to "break the contract". As per the API, the result returned from the hashCode() method for two objects must be the same if their equals methods show that they are equivalent. The converse is not necessarily true.

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).

String.equals versus ==

Use the string.equals(Object other) function to compare strings, not the == operator.

The function checks the actual contents of the string, the == operator checks whether the references to the objects are equal. Note that string constants are usually "interned" such that two constants with the same value can actually be compared with ==, but it's better not to rely on that.

if (usuario.equals(datos[0])) {
...
}

NB: the compare is done on 'usuario' because that's guaranteed non-null in your code, although you should still check that you've actually got some tokens in the datos array otherwise you'll get an array-out-of-bounds exception.

== or .Equals()

== is the identity test. It will return true if the two objects being tested are in fact the same object. Equals() performs an equality test, and will return true if the two objects consider themselves equal.

Identity testing is faster, so you can use it when there's no need for more expensive equality tests. For example, comparing against null or the empty string.

It's possible to overload either of these to provide different behavior -- like identity testing for Equals() --, but for the sake of anybody reading your code, please don't.


Pointed out below: some types like String or DateTime provide overloads for the == operator that give it equality semantics. So the exact behavior will depend on the types of the objects you are comparing.


See also:

  • http://blogs.msdn.com/csharpfaq/archive/2004/03/29/102224.aspx

C# difference between == and Equals()

When == is used on an expression of type object, it'll resolve to System.Object.ReferenceEquals.

Equals is just a virtual method and behaves as such, so the overridden version will be used (which, for string type compares the contents).

What's the difference between == and .equals in Scala?

You normally use ==, it routes to equals, except that it treats nulls properly. Reference equality (rarely used) is eq.

Is == operator faster than equals()?

TL;DR Don't use == to compare strings.

Specifically with regard to strings, yes, == is slightly faster than equals, because the first thing the String.equals method does is...a == comparison to see if the string is being compared to itself. If it is, equals() is slower by the cost of a method call. If it isn't, equals is slower by that cost plus the cost of comparing the characters in the strings.

But remember that before you can use == to compare strings (which is a Bad Idea™), you have to know for sure that both strings are interned. The combination of intern() and == is not faster than equals(). intern() is a relatively expensive operation, as it involves looking for an equivalent string already in the intern pool, which may involve lots and lots of equals() calls (or their equivalent).

There may be some extremely rare edge cases where it's reasonable to incur that intern() cost and then use == on strings you know are interned. For instance, if you have a large static set of strings that you compare to one another really frequently. But that's an extremely unusual edge situation.

Bottom line: Don't compare strings with ==. Don't intern strings unnecessarily.

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).

Performance of == vs Equals in generic C# class

The reason being that == defaults to reference equality and that makes no sense for value types, the answer will always be false. Because there is no language mechanism to constrain generic types based upon static methods, the compiler simply disallows this as it can't verify that T really has an overloaded == operator.

On the other hand if you constraint T to class it will compile just fine because reference equality does make sense for reference types.

The solution is of course IEquatable<T>; in any sanely implemented struct IEquatable<T>.Equals(T t) will give you value equality semantics and == should behave consistently.

And answering your question, no there is not. If you really need the speed of int == int you will need to implement a non generic specialized class.



Related Topics



Leave a reply



Submit