简体   繁体   中英

Difference between Equals/equals and == operator?

a == ba.Equals(b)之间a == b什么区别?

Assuming the types of a and b are reference types:

  • In Java, == will always compare for identity - ie whether the two values are references to the same object. This is also called reference equality . Java doesn't have any user-defined operator overloading.

  • In C# it depends. Unless there's an overloaded operator which handles it, == will behave like Java (ie comparing for reference equality). However, if there's an overload which matches the compile-time types of a and b (eg if they're both declared as strings) then that overload will be called. That can behave how it wants, but it typically implements value equality (ie a and b can refer to different but equal values and it would still return true).

In both languages, a.Equals(b) or a.equals(b) will call the virtual Equals / equals method declared by Object , unless a more specific overload has been introduced by the compile-time type of a . This may or may not be overridden in the execution-time type of the object that a refers to. In both .NET and Java, the implementation in Object also checks for identity. Note that this depends on the execution-time type rather than the compilation-time type that overload resolution depends on.

Of course, if a is null then you'll get a NullReferenceException / NullPointerException when you try to call a.equals(b) or a.Equals(b) .

The == operator checks to see if two objects are exactly the same object which is not the way to go in most cases. The Equals method will be able to compare both the object internally

Example:

class Mycar
{
  string color;
  Mycar(string str)
 {
   color = str;
 }
}   

Mycar a = new Mycar("blue");
Mycar b = new Mycar("blue");
a==b // Returns false
a.Equals(b) // Returns true

It depends on the types of a and b .

In particular, Equals is a virtual method, so that its behavior doesn't depend on the compile-time types of a and b.

In Java, == will always compare by reference, which is not necessarily what you want, especially for strings.

In C#, == can be overloaded, but is not virtual (it's a static method). Therefore, if a or b are declared as object , it will compare by reference, even if their actual type overloads operator == .

Also, a.Equals(b) will throw a NullReferenceException ( NullPointerException in Java) if a is null .

String a = "toto".Substring(0, 4);
String b = "toto";
Object aAsObj = a;
Assert.IsTrue(a.Equals(b));
Assert.IsTrue(a == b);
Assert.IsFalse(aAsObj == b);
Assert.IsTrue(aAsObj.Equals(b));

This test pass in .NET, the trick is that Equals is a method, whereas == is a static method, so aAsObj == b use

static bool Object.operator==(object a, object b) //Reference comparison

whereas a == b use

static bool String.operator==(string a, string b) //String comparison

but a.Equals(b) or aAsObj.Equals(b) always use :

bool String.Equals(Object obj) //String comparison

== is a fundamental operator in the language. The operator == tests to see if two object reference variables refer to the exact same instance of an object.

equals () is an instance method which is fundamentally defined by the java.lang.Object class. The method, .equals() tests to see if the two objects being compared to each other are equivalent , but they need not be the exact same instance of the same object.

The == operator always gives you the same result, but the equals () method gives you output according to your implementation (implemented logic).Proper overriding of equals: Considerations' whenever overriding equals () method.

1. Reflexive: For any non-null reference x, x.equals(x) should return true.

2. Symmetric: For any non-null reference x and y, if x.equals(y) is true then y.equals(x) must return true.

3. Transitive: For any non-null reference x , y and z, if x.equals(y) is true, y.equals(z) is true then x.equals(z) must return true.

4. Consistent: For any non-null reference x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, without changing the information provided for the equals comparisons.

5. For any non-null reference x, x.equals (null) must return false. NOTE: If o1.equals (o2) is true then o1.hashcode () ==o2.hashcode (), but the reverse may or may not be true.

Examples:

Integer i = new Integer(10); Integer j = i;

in the above code. i == j is true because both i and j refer to the same object.

Integer i = new Integer (10); Integer j = new Integer(10);

In the above code, i == j is FALSE because, although they both have the value 10, they are two different objects. But i.equals (j) will return true.

Using Auto-boxing

Integer i = 10;
Integer j = 10;
Boolean b = (i == j);
System.out.println (b);

This will return TRUE because integers between ranges -127 to 128 be pooled, so in this case both are same objects (JVM not going to create a new object it will retrieve it from pool).

String class overrides the equals method, so here is an example of equals vs. == String s1 = new String ("abc"); String s2 = new String ("abc");

NOTE: Strings are created in String constant pool so when we create like String s=”abc” it will check the pool by invoking the native method intern (), for its existence in the existing pool if it did not found any String then it will create new one but if we invoke new operator then it will create one new String irrespective of checking the pool for existence.

  public class StringEqualityTest {
    public static void main(String []a){

    String s1=new String("abc");
    String s2=new String("abc");

     System.out.print("s1.equals(s2)  :"+s1.equals(s2)+"  s1==s2   :");
     System.out.println(s1==s2);

     String s3="abc";
     String s4="abc";

     System.out.print("s3.equals(s4)  :"+s1.equals(s2)+"  s3==s4   :");
     System.out.println(s3==s4);

       }

       }

OUTPUT: s1.equals(s2) :true s1==s2 :false s3.equals(s4) :true s3==s4 :true

a == b returns true if the references contain the same value, ie, they point to the same object, or they are both null.

The equals() method can be overridden to compare objects. For example, on Strings , the method returns true if the strings contain the same string, even if they are different string objects. You can do similar things with your own objects.

o.equals() will throw an exception if o is a null reference.

Suppose we have a and b or two different objects and we want to compare these two object references. Then we use the == operator and when using a.equals(b) , it compares the string values.

== checks if references are pointing to the same object in the memory

Now,

although the code of equals method in object class is nothing but checking == for the references, it can be overridden to add your own equality checks.

In classes like String, the overridden method checks if the string literals are correct or not. So basically it can be used to check if value is same or not.

== checks the Object reference, basically it compares the hashcodes. Equals uses the contents in the object. Remember, we have to override the .equals method accordingly in our class.

== uses the reference of an object, or if an integer/float etc, then it compares the actual number. Technically it just compares what in the memory location. Whereas .equals uses a method inside the object class to compare objects, it can be overridden for your individual classes. Also as arrays also deal with references, its also helpful not to use array1[i] = array2[i] , use arraycopy or clone() . I think .equals can also be used with arrays

==,它只返回一个哈希码的值根据它们的地址所以不同的地址,即使字符串或任何相似的数据也返回false ....这是条件的完全帮助,返回布尔值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM