خرید بک لینک

Vote count: 202

I wanted to clarify if I understand this correctly:

  • == -> is a reference comparison, i.e. both objects point to the same memory location
  • .equals() -> evaluates to the comparison of values in the objects

Am I correct in my understanding ?

asked Sep 22 '11 at 19:36

16 Answers

Vote count: 252 accepted

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 retus 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 retued from the hashCode() method for two objects must be the same if their equals methods shows that they are equivalent. The converse is not necessarily true.
answered Sep 22 '11 at 19:39

Vote count: 35

With respect to the String class:

The equals() method compares the "value" inside String instances (on the heap) irrespective if the two object references refer to the same String instance or not. If any two object references of type String refer to the same String instance then great! If the two object references refer to two different String instances .. it doesn't make a difference. Its the "value" (that is: the contents of the character array) inside each String instance that is being compared.

On the other hand, the "==" operator compares the value of two object references to see whether they refer to the same String instance. If the value of both object references "refer to" the same String instance then the result of the boolean expression would be "true"..duh. If, on the other hand, the value of both object references "refer to" different String instances (even though both String instances have identical "values", that is, the contents of the character arrays of each String instance are the same) the result of the boolean expression would be "false".

As with any explanation, let it sink in.

I hope this clears things up a bit.

answered May 29 '12 at 20:24

Vote count: 13

There are some small differences depending whether you are talking about "primitives" or "Object Types"; the same can be said if you are talking about "static" or "non-static" members; you can also mix all the above...

Here is an example (you can run it):

public final class MyEqualityTest
{
    public static void main( String args[] )
    {
        String s1 = new String( "Test" );
        String s2 = new String( "Test" );

        System.out.println( "n1 - PRIMITIVES ");
        System.out.println( s1 == s2 ); // false
        System.out.println( s1.equals( s2 )); // true

        A a1 = new A();
        A a2 = new A();

        System.out.println( "n2 - OBJECT TYPES / STATIC VARIABLE" );
        System.out.println( a1 == a2 ); // false
        System.out.println( a1.s == a2.s ); // true
        System.out.println( a1.s.equals( a2.s ) ); // true

        B b1 = new B();
        B b2 = new B();

        System.out.println( "n3 - OBJECT TYPES / NON-STATIC VARIABLE" );
        System.out.println( b1 == b2 ); // false
        System.out.println( b1.getS() == b2.getS() ); // false
        System.out.println( b1.getS().equals( b2.getS() ) ); // true
    }
}

final class A
{
    // static
    public static String s;
    A()
    {
        this.s = new String( "aTest" );
    }
}

final class B
{
    private String s;
    B()
    {
        this.s = new String( "aTest" );
    }

    public String getS()
    {
        retu s;
    }

}

You can compare the explanations for "==" (Equality Operator) and ".equals(...)" (method in the java.lang.Object class) through these links:

answered Mar 6 '14 at 1:56

Vote count: 8

You will have to override the equals function (along with others) to use this with custom classes.

The equals method compares the objects.

The == binary operator compares mem addresses.

answered Sep 22 '11 at 19:39

Vote count: 3

Both == and .equals() refers to the same object if you don't override .equals().

Its your wish what you want to do once you override .equals(). You can compare the invoking object's state with the passed in object's state or you can just call super.equals()

answered Sep 22 '11 at 19:54

Vote count: 3

Just remember that .equals(...) has to be implemented by the class you are trying to compare. Otherwise, there isn't much of a point; the version of the method for the Object class does the same thing as the comparison operation: Object#equals.

The only time you really want to use the comparison operator for objects is wen you are comparing Enums. This is because there is only one instance of an Enum value at a time. For instance, given the enum

enum FooEnum {A, B, C}

You will never have more than one instance of A at a time, and the same for B and C. This means that you can actually write a method like so:

public boolean compareFoos(FooEnum x, FooEnum y)
{
    retu (x == y);
}

And you will have no problems whatsoever.

answered Sep 22 '11 at 21:22

Vote count: 2

"==" is an operator and "equals" is a method. operators are used for primitive type comparisons and so "==" is used for memory address comparison."equals" method is used for comparing objects.

answered Jan 15 '14 at 3:23

Vote count: 2

The == operator:

The == is a relational operator in Java that is used to compare two operands. It is used to determine whether the two operands are equal or not. Using the == operator, you can compare any primitive type such as int, char, float and Booleans. After comparison, the == operator retus a boolean value. If the two operands are equal, the == operator retus a true value. However, if the two operands are not equal, it retus a false value. When used with objects, the == operator compares the two object references and determines whether they refer to the same instance.

The .equals() Method

equals() is a method available in the String class that is used to compare two strings and determine whether they are equal. This method retus a boolean value as a result of the comparison. If the two strings contain the same characters in the same order, the equals() method retus true. Otherwise, it retus a false value.

For Examples:

http://goo.gl/Sa3q5Y

answered Sep 29 '15 at 3:54

Vote count: 1

Also note that .equals() normally contains == for testing as this is the first thing you would wish to test for if you wanted to test if two objects are equal.

And == actually does look at values for primitive types, for objects it checks the reference.

answered Mar 24 '15 at 6:15

Vote count: 1

== operator always reference is compared. But in case of

equals() method

it's depends's on implementation if we are overridden equals method than it compares object on basic of implementation given in overridden method.

 class A
 {
   int id;
   String str;

     public A(int id,String str)
     {
       this.id=id;
       this.str=str;
     }

    public static void main(String arg[])
    {
      A obj=new A(101,"sam");
      A obj1=new A(101,"sam");

      obj.equals(obj1)//fasle
      obj==obj1 // fasle
    }
 }

in above code both obj and obj1 object contains same data but reference is not same so equals retu false and == also. but if we overridden equals method than

 class A
 {
   int id;
   String str;

     public A(int id,String str)
     {
       this.id=id;
       this.str=str;
     }
    public boolean equals(Object obj)
    {
       A a1=(A)obj;
      retu this.id==a1.id;
    }

    public static void main(String arg[])
    {
      A obj=new A(101,"sam");
      A obj1=new A(101,"sam");

      obj.equals(obj1)//true
      obj==obj1 // fasle
    }
 }

know check out it will retu true and false for same case only we overridden

equals method .

it compare object on basic of content(id) of object

but ==

still compare references of object.

answered Feb 3 at 17:48

Vote count: 1

Difference between == and equals confused me for sometime until I decided to have a closer look at it. Many of them say that for comparing string you should use equals and not ==. Hope in this answer I will be able to say the difference.

The best way to answer this question will be by asking few question to yourself. so lets start:

What is the output for the below program:

String mango = "mango";
String mango2 = "mango";
System.out.println(mango != mango2);
System.out.println(mango == mango2);

if you say,

false
true

I will say you are right but why did you said that? and If you say the output is,

true
false

I will say you are wrong but I will still ask you, why you think that is right?

Ok, Lets try to answer this one:

What is the output for the below program:

String mango = "mango";
String mango3 = new String("mango");
System.out.println(mango != mango3);
System.out.println(mango == mango3);

Now If you say,

false
true

I will say you are wrong but why is it wrong now? the correct output for this program is

true
false

Please compare the above program and try to think on it.

Ok. Now this might help (please read this : print the address of object - not possible but still we can use it.)

String mango = "mango";
String mango2 = "mango";
String mango3 = new String("mango");
System.out.println(mango != mango2);
System.out.println(mango == mango2);
System.out.println(mango3 != mango2);
System.out.println(mango3 == mango2);
// mango2 = "mang";
System.out.println(mango+" "+ mango2);
System.out.println(mango != mango2);
System.out.println(mango == mango2);

System.out.println(System.identityHashCode(mango));
System.out.println(System.identityHashCode(mango2));
System.out.println(System.identityHashCode(mango3));

can you just try to think for the output of last three lines in above code: for me ideone printed this out (you can check the code here):

false
true
true
false
mango mango
false
true
17225372
17225372
5433634

Oh! Now you see the identityHashCode(mango) is equal to identityHashCode(mango2) But it is not equal to identityHashCode(mango3)

Even though all the string variables - mango,mango2 and mango3 has the same value of "mango". But still identityHashCode() for all is not same.

Now try to uncomment this line // mango2 = "mang"; and run it again this time you will see all three identityHashCode() are different. Hmm that is a helpful hint

we know that if hashcode(x)=N and hashcode(y)=N => x is equal to y

I am not sure how java works inteally, But I assume this is what happened when I said:

mango = "mango";

java created a string "mango" and which was pointed(referenced) by variable mango something like this

mango ----> "mango"

Now in the next line when I said:

mango2 = "mango";

It actually reused the same string "mango" which looks something like this

mango ----> "mango" <---- mango2

Both mango and mango2 pointing to the same reference Now when I said

mango3 = new String("mango")

It actually created a completely new reference(string) for "mango". which looks something like this,

mango -----> "mango" <------ mango2

mango3 ------> "mango"

and thats why when I outputted the values for mango == mango2, it outputted true. and when I outputted the value for mango3 == mango2, it outputted false (even when the value were same).

and when you uncommented the line // mango2 = "mang"; It actually created a string "mang" and which tued our graph like this:

mango ---->"mango"
mango2 ----> "mang"
mango3 -----> "mango"

and this is why the identityHashCode is not same for all.

Hope this help you guys. Actually I wanted to generate a testcase where == fails and equals() pass. Please feel free to comment and let me know If I am wrong.

Sorry for the long answer and sorry for the improper graph. Wrote the answer just so that I can help you and me. Thank you.

answered Apr 5 at 10:55

Vote count: 0

It may be worth adding that for wrapper objects for primitive types - i.e. Int, Long, Double - equals will retu true if the two values are equal.

Long a = 10L;
Long b = 10L;

if (a.equals(b)) {
    System.out.println("Wrapped primitives behave like values");
}

answered Dec 12 '14 at 18:44

Vote count: 0

== can be used in many object types but you can use Object.equals for any type , especially Strings and Google Map Markers.

answered Dec 15 '14 at 6:05

Vote count: 0

Since Java doesn’t support operator overloading, == behaves identical for every object but equals() is method, which can be overridden in Java and logic to compare objects can be changed based upon business rules.

Main difference between == and equals in Java is that "==" is used to compare primitives while equals() method is recommended to check equality of objects.

String comparison is a common scenario of using both == and equals method. Since java.lang.String class override equals method, It retu true if two String object contains same content but == will only retu true if two references are pointing to same object.

Here is an example of comparing two Strings in Java for equality using == and equals() method which will clear some doubts:

public class TEstT{

    public static void main(String[] args) {

String text1 = new String("apple");
String text2 = new String("apple");

//since two strings are different object result should be false
boolean result = text1 == text2;
System.out.println("Comparing two strings with == operator: " + result);

//since strings contains same content , equals() should retu true
result = text1.equals(text2);
System.out.println("Comparing two Strings with same content using equals method: " + result);

text2 = text1;
//since both text2 and text1d reference variable are pointing to same object
//"==" should retu true
result = (text1 == text2);
System.out.println("Comparing two reference pointing to same String with == operator: " + result);

}
}

answered Feb 2 '15 at 12:03

Vote count: 0

The String pool (aka inteing) and Integer pool blur the difference further, and may allow you to use == for objects in some cases instead of .equals

This can give you greater performance (?), at the cost of greater complexity.

E.g.:

assert "ab" == "a" + "b";

Integer i = 1;
Integer j = i;
assert i == j;

Complexity tradeoff: the following may surprise you:

assert new String("a") != new String("a");

Integer i = 128;
Integer j = 128;
assert i != j;

I advise you to stay away from such micro-optimization, and always use .equals for objects, and == for primitives:

assert (new String("a")).equals(new String("a"));

Integer i = 128;
Integer j = 128;
assert i.equals(j);

answered Feb 14 at 23:35

Vote count: 0

Basically, == compares if two objects have the same reference on the heap, so unless two references are linked to the same object, this comparison will be false.

equals() is a method inherited from Object class. This method by default compares if two objects have the same referece. It means:

object1.equals(object2) <=> object1 == object2

However, if you want to establish equality between two objects of the same class you should override this method. It is also very important to override the method hashCode() if you have overriden equals().

Implement hashCode() when establishing equality is part of the Java Object Contract. If you are working with collections, and you haven't implemented hashCode(), Strange Bad Things could happen:

HashMap<Cat, String> cats = new HashMap<>();
Cat cat = new Cat("molly");
cats.put(cat, "This is a cool cat");
System.out.println(cats.get(new Cat("molly"));

null will be printed after executing the previous code if you haven't implemented hashCode().

answered Apr 26 at 21:20

برچسب: نویسنده: استخدام کار تاريخ: پنجشنبه 17 تير 1395 ساعت: 2:35

صفحه بندی