Differences between "=" and "Equal" in java

Source: Internet
Author: User
Tags comparison hash


For some basic data types, int, long, bool, and char !, "=" Indicates that the values are equal and there is no equal method.

The equal method is the method in the object. In java, String is not a basic data type, but a class. They all inherit the object class, and the difference between Integer and int is that Integer is a class!

In the object class, the equal method is equivalent to "=". "=" does not mean that the value is equal, but compares whether the object address is equal! Both Integer and String are overwritten (yes! Rewrite is to rewrite the function. The overload is to write multiple functions with the same name but different parameters. The rewrite is to redefine the method of the parent class, reflecting the polymorphism ), after the equal method is rewritten by String and Integer, it is a comparison value rather than an address.


= The Operation compares whether the values of two variables are equal. For a referenced variable, it indicates whether the addresses of the two variables stored in the heap are the same, that is, whether the stack content is the same.

The equals operation indicates whether the two variables are referenced to the same object, that is, whether the content in the heap is the same.

= Compare the addresses of two objects, while equals compares the content of two objects.

Obviously, when equals is true, ==is not necessarily set to true;

I. equals and = in String

1,

Public class TestString {

Public static void main (String [] args ){

String s1 = "Monday ";

String s2 = "Monday ";

    }

    }

In the above section, how many objects are there?

Check the program. Modify the program slightly.

Public class TestString {

Public static void main (String [] args ){

String s1 = "Monday ";

String s2 = "Monday ";

If (s1 = s2)

System. out. println ("s1 = s2 ");

Else

System. out. println ("s1! = S2 ");

    }

    }

Compile and run the program. Output: s1 = s2 description: s1 and s2 reference the same String object -- "Monday "!

2. If you change the program a little bit, you may find it strange:

Public class TestString {

Public static void main (String [] args ){

String s1 = "Monday ";

String s2 = new String ("Monday ");

If (s1 = s2)

System. out. println ("s1 = s2 ");

Else

System. out. println ("s1! = S2 ");

If (s1.equals (s2) System. out. println ("s1 equals s2 ");

Else

System. out. println ("s1 not equals s2 ");

    }

    }

We will create s2 with the new operator

Program output:

S1! = S2

S1 equals s2

Note: s1 s2 references two "Monday" String objects respectively.

3. STRING buffer pool

It turns out that the program will create a string buffer pool when running. When expression s2 = "Monday" is used to create a string, the program first searches for objects with the same value in the String buffer pool. In the first program, s1 is first placed in the pool. Therefore, when s2 is created, the program finds s1 with the same value

Reference s2 to the object referenced by s1 "Monday"

In the second stage, the new operator is used, and he clearly tells the program: "I want a new one! Don't be old! "So a new" Monday "Sting object is created in the memory. They have the same value but different locations. One is swimming in the pool and the other is resting on the shore. Oh, it's a waste of resources. What should we do separately?

4.

Change the program again:

Public class TestString {

Public static void main (String [] args ){

String s1 = "Monday ";

String s2 = new String ("Monday ");

S2 = s2.intern ();

If (s1 = s2)

System. out. println ("s1 = s2 ");

Else

System. out. println ("s1! = S2 ");

If (s1.equals (s2) System. out. println ("s1 equals s2 ");

Else

System. out. println ("s1 not equals s2 ");

    }

    }

Join this time: s2 = s2.intern ();

Program output:

S1 = s2

S1 equals s2

Originally, the return value of the (java. lang. String's intern () method "abc". intern () method is still the String "abc". On the surface, it seems that this method is useless. But in fact, it performs a small action: Check whether there is a string such as "abc" in the string pool. If yes, the string in the pool is returned; if not, this method adds "abc" to the string pool and then returns its reference.

)

Better solution:

Set all strings to intern () to the buffer pool.

It is best to perform this operation when new is used.

String s2 = new String ("Monday"). intern ();

Then we can use = to compare the values of two strings.

 

II. equals and = in simple data types and encapsulation classes

Java provides an encapsulation class for each simple data type. Each basic data type can be encapsulated into an object type.

In addition to int (Integer) and char (Character), the first letter of other types is an encapsulation class name. Double (Double), float (Float), long (Long), short (Short), byte (Byte), boolean (Boolean ).

Int and Integer are used as examples.

The difference between int and Integer in Java is as follows:

1.int is the basic data type. The default value can be 0. 2. integer is an int encapsulation class. The default value is null. Both 3.int and Integer can indicate a certain value. 4.int and Integer cannot be used with each other because they have two different data types;

Int a1 = 1;

Int a2 = 1;

Integer b1 = new Integer (1 );

Integer b2 = new Integer (1 );

------------------------------

A1 = a2: this is true. It is very simple. We all know that a1 = b1 is not true. the expression value is false. They are of different data types b1 = b2, which is also not true. the expression value is false. Although it is of the same data type, they are two objects. = compares the addresses of two objects, and their addresses are not equal, the same content is 1;

B1.equals (b2) = true this is true, and the expression value is true. for the same data type, two objects have different addresses and the content is the same. quals compares the content of two objects, so it is true.

(A. equals (B). Since equals compares two objects, neither a nor B can be of the basic data type. Otherwise, a compilation error occurs .) Similarly, other encapsulation classes and basic types are the same.

Differences between equals and = in java

= Compare the addresses of two objects, while equals compares the content of two objects.

III. How to use equals and = for other classes

Most of the classes in the API are overwritten by the equals method. The classes that are not overwritten are generally self-written classes. If they are a class defined by yourself, compared with custom classes, equals and = are the same. They both compare the handle address, because the custom class inherits from the object, and the equals in the object is implemented using =, you can see the source code.

4. What is the relationship between equals and hashCode in java?

The hashCode of the two objects compared with equals must be the same only to maintain the regular protocol of the hashCode method. both equals () and hashCode () come from java. lang. object. of course you can rewrite it.

For example,. equals (B ). true is returned only when the memory address of a is equal. of course, this method has been rewritten for classes such as String, and the comparison is no longer the memory address. the value of hashCode () is also related to the memory address. therefore, hashCode is equal only when the memory address is equal.

This method is also overwritten by many classes. The following uses String as an example:

Public int hashCode (){

Int h = hash;

If (h = 0 ){

Int off = offset;

Char val [] = value;

Int len = count;

For (int I = 0; I <len; I ++ ){

H = 31 * h + val [off ++];

    }

Hash = h;

    }

Return h;

    }

It is not related to the memory address. This is done to ensure that the two objects returned as true are compared with equals, and their hashCode is the same.

Therefore, hashCode () is overwritten when equals is rewritten. Of course, this is equivalent to a convention and a protocol. If you do not do this, it will not be wrong.

 

Example

Public class Upload test {
Public static void main (String [] args ){
// For variables of the basic type. "=" And "equal"
Int t1 = 57;
Int t2 = 67;
Int t3 = 124;
Int t4 = 124;
   
// "=" Determines whether the values of the two variables are equal for the basic data type.
Boolean result1 = (t1 = t2 );
Boolean result2 = (t1 + t2) = t3 );
Boolean result3 = (t3 = t4 );
   
System. out. println ("\ n ----- [t1 = t2]" + result1 + "\ n ----- [(t1 + t2) = t3] "+ result2 +" \ n ----- [t3 = t4] "+ result3 );
// "Equal" cannot be used for basic data types. It can only be used for class variables. Use the package class for basic data types.
Integer i1 = new Integer (t1 );
Integer i2 = new Integer (t2 );
Integer i3 = new Integer (t3 );
Integer i4 = new Integer (t4 );
   
   
Boolean ri1 = i1.equals (i2 );
Boolean ri2 = i3.equals (i1 + i2 );
Boolean ri3 = i3.equals (i4 );
   
System. out. println ("\ n ----- [i1.equals (i2)]" + ri1 + "\ n ----- [i3.equals (i1 + i2)] "+ ri2 +" \ n ----- [i3.equals (i4)] "+ ri3 );
 
// The difference between "=" and "equal" for object variables
String st1 = "wasiker ";
String st2 = "is super man ";
String st3 = "wasiker is super man ";
String st4 = "wasiker is super man ";
   
Boolean b1 = (st1 = st2 );
Boolean b2 = (st1 + st2) = st3;
Boolean b3 = (st3 = st4 );
   
System. out. println ("\ n ----- [st1 = st2]" + b1 + "\ n ----- [(st1 + st2) = st3] "+ b2 +" \ n ----- [st3 = st4] "+ b3 );
// Because the object variable stores the path of the object in the memory, that is, the memory address. Therefore, when "=" is used for comparison
// The object values are equal, but their memory addresses are different, so the result of = is false. Therefore, "=" is used to compare two
// Whether the values of variables are equal, rather than whether the objects referenced by variables are equal
Boolean r1 = st1.equals (st2 );
Boolean r2 = (st1 + st2). equals (st3 );
Boolean r3 = st3.equals (st4 );
   
System. out. println ("\ n ----- [st1.equals (st2)]" + r1 + "\ n ----- [(st1 + st2 ). equals (st3)] "+ r2 +" \ n ----- [st3.equals (st4)] "+ r3 );
// Equal is used to compare whether two objects are the same.
}
}
The running result is:
----- [T1 = t2] false
----- [(T1 + t2) = t3] true
----- [T3 = t4] true
----- [I1.equals (i2)] false
----- [I3.equals (i1 + i2)] true
----- [I3.equals (i4)] true
----- [St1 = st2] false
----- [(St1 + st2) = st3] false
----- [St3 = st4] true
----- [St1.equals (st2)] false
----- [(St1 + st2). equals (st3)] true
----- [St3.equals (st4)] true

In short:

"=" Compares the value [the (heap) memory address of the object stored in the variable (stack) memory]
Equal is used to compare whether the values of two objects are the same [not a specific address]
[Note] the equals method in the Object class is the same as "=" and there is no difference. Some classes such as the String class and Integer class override the equals method, so that when you create a class, the equals method of the Object is automatically inherited. To implement different equals comparisons, you must override the equals method.
"=" Is faster than "equal" because "=" is just a reference.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.