What's the Difference Between ".Equals" and "=="

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 .equals and ==?

In Java, == always just compares two references (for non-primitives, that is) - i.e. it tests whether the two operands refer to the same object.

However, the equals method can be overridden - so two distinct objects can still be equal.

For example:

String x = "hello";
String y = new String(new char[] { 'h', 'e', 'l', 'l', 'o' });

System.out.println(x == y); // false
System.out.println(x.equals(y)); // true

Additionally, it's worth being aware that any two equal string constants (primarily string literals, but also combinations of string constants via concatenation) will end up referring to the same string. For example:

String x = "hello";
String y = "he" + "llo";
System.out.println(x == y); // true!

Here x and y are references to the same string, because y is a compile-time constant equal to "hello".

Java, what's the difference between == and equals

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

What is the difference between .Equals and ==

From When should I use Equals and when should I use ==:

The Equals method is just a virtual
one defined in System.Object, and
overridden by whichever classes choose
to do so. The == operator is an
operator which can be overloaded by
classes, but which usually has
identity behaviour.

For reference types where == has not
been overloaded, it compares whether
two references refer to the same
object - which is exactly what the
implementation of Equals does in
System.Object.

Value types do not provide an overload
for == by default. However, most of
the value types provided by the
framework provide their own overload.
The default implementation of Equals
for a value type is provided by
ValueType, and uses reflection to make
the comparison, which makes it
significantly slower than a
type-specific implementation normally
would be. This implementation also
calls Equals on pairs of references
within the two values being compared.

using System;

public class Test
{
static void Main()
{
// Create two equal but distinct strings
string a = new string(new char[] {'h', 'e', 'l', 'l', 'o'});
string b = new string(new char[] {'h', 'e', 'l', 'l', 'o'});

Console.WriteLine (a==b);
Console.WriteLine (a.Equals(b));

// Now let's see what happens with the same tests but
// with variables of type object
object c = a;
object d = b;

Console.WriteLine (c==d);
Console.WriteLine (c.Equals(d));
}
}

The result of this short sample program is

True
True
False
True

What’s difference between equals and contains

The String equals() method compares the two given strings based on the content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true. For your scenario, you would look through every String in your List, compare it with the String you want and return true if they are the same.

The ArrayList.contains(Object) method returns true if this List contains the specified element. The actual implementation of the contains method in java.util.ArrayList is the following:

/**
* Returns true iff element is in this ArrayList.
*
* @param e the element whose inclusion in the List is being tested
* @return true if the list contains e
*/
public boolean contains(Object e)
{
return indexOf(e) != -1;
}

The indexOf() method of ArrayList returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

Whatever approach you decide to take, either is acceptable. In specifically your case, since you have a hard-coded value that you are checking, in my opinion it would look neater to use the contains method, but that is not a single correct answer.

What is the difference between == and Equals() for primitives in C#?

Short answer:

Equality is complicated.

Detailed answer:

Primitives types override the base object.Equals(object) and return true if the boxed object is of the same type and value. (Note that it will also work for nullable types; non-null nullable types always box to an instance of the underlying type.)

Since newAge is a short, its Equals(object) method only returns true if you pass a boxed short with the same value. You're passing a boxed int, so it returns false.

By contrast, the == operator is defined as taking two ints (or shorts or longs).

When you call it with an int and a short, the compiler will implicitly convert the short to int and compare the resulting ints by value.

Other ways to make it work

Primitive types also have their own Equals() method that accepts the same type.

If you write age.Equals(newAge), the compiler will select int.Equals(int) as the best overload and implicitly convert short to int. It will then return true, since this method simply compares the ints directly.

short also has a short.Equals(short) method, but int cannot be implicitly converted to short, so you aren't calling it.

You could force it to call this method with a cast:

Console.WriteLine(newAge.Equals((short)age)); // true

This will call short.Equals(short) directly, without boxing. If age is larger than 32767, it will throw an overflow exception.

You could also call the short.Equals(object) overload, but explicitly pass a boxed object so that it gets the same type:

Console.WriteLine(newAge.Equals((object)(short)age)); // true

Like the previous alternative, this will throw an overflow if it doesn't fit in a short.
Unlike the previous solution, it will box the short into an object, wasting time and memory.

Source Code:

Here are both Equals() methods from the actual source code:

    public override bool Equals(Object obj) {
if (!(obj is Int16)) {
return false;
}
return m_value == ((Int16)obj).m_value;
}

public bool Equals(Int16 obj)
{
return m_value == obj;
}

Further Reading:

See Eric Lippert.

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.

what is the difference between equals() and equalsIgnoreCase() in StringUtils of commons-lang3-3.6.jar?

the difference is in a method CharSequenceUtils.regionMatches . The second parameter is ignoreCase

static boolean regionMatches(CharSequence cs, boolean ignoreCase, int thisStart,
CharSequence substring, int start, int length) {
if (cs instanceof String && substring instanceof String) {
return ((String) cs).regionMatches(ignoreCase, thisStart, ((String) substring), start, length);
} else {
// TODO: Implement rather than convert to String
return cs.toString().regionMatches(ignoreCase, thisStart, substring.toString(), start, length);
}
}


Related Topics



Leave a reply



Submit