Differences between equals and = in Java

Source: Internet
Author: User

From: http://daimajishu.iteye.com/blog/1081090

 

The value type is the stack stored in the memory (later referred to as the stack), while the reference type variable only stores the address of the reference type variable in the stack, and its own is stored in the heap.
= 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 ";
}
}
The above sectionProgramHow 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
Note: 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

originally, a string buffer pool is created when the program is running.
when the expression S2 = "Monday" is used to create a string, the program first finds 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
references S2 to the object "Monday" referenced by S1
In the second program, the new operator is used, he clearly told 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.
the other is resting on the shore. Oh, it's a waste of resources. What should we do separately?
4.
program change 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");
}< br> join this time: S2 = s2.intern ();
program output:
S1 = S2
S1 equals S2

Originally, (Java. Lang. String's intern () method
The return value of the "ABC". Intern () method is still the string "ABC". On the surface, it seems that this method is useless. But in fact, it does a little action:
Check whether there is a string such as "ABC" in the string pool. If yes, the string in the pool is returned. If no, this method adds "ABC" to the string pool, then return 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;
3.int and integer can both represent a value;
4.int and integer cannot interwork 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 an established one. It's very simple and we all know it.
A1 = b1 this is not true. The expression value is false. They are different data types (true in JDK or a later version)
B1 = b2 this 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 .) (In jdk1.5 or later versions, B can be the basic data type, but a cannot)
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.

In JDK or later versions, the basic type and encapsulation class can be automatically converted, similar to the string type object and String constant.
Integer I1 = 123;
Integer I2 = 123;

Int I = 123;

Integer I3 = new INTEGER (123 );
Integer I4 = new INTEGER (123 );

System. Out. println ("I1 = I2 =" + (I1 = I2 ));
System. Out. println ("i1.equals (I2) =" + (i1.equals (I2 )));

System. Out. println ();
System. Out. println ("I3 = I4 =" + (I3 = I4 ));
System. Out. println ("i3.equals (I4) =" + (i3.equals (I4 )));

System. Out. println ();
System. Out. println ("I2 = I4 =" + (I2 = I4 ));
System. Out. println ("i2.equals (I4) =" + (i2.equals (I4 )));

System. Out. println ();
System. Out. println ("I = I2 =" + (I = I2 ));
System. Out. println ("i1.equals (I) =" + (i1.equals (I )));

System. Out. println ();
System. Out. println ("I = I4 =" + (I = I4 ));
System. Out. println ("i4.equals (I) =" + (i4.equals (I )));

------------------------------
I1 = I2 = true
I1.equals (I2) = true

I3 = I4 = false
I3.equals (I4) = true

I2 = I4 = false
I2.equals (I4) = true

I = I2 = true
I1.equals (I) = true

I = I4 = true
I4.equals (I) = true

Iii. How to Use equals and = for other classes
Most of the classes in the API are overwritten by the equals method. Classes written by themselves are not overwritten,
If you define a class by yourself and compare custom classes with equals and =, they all compare the handle addresses,
Because the custom class inherits from the object, and the equals in the object is implemented with =, you can refer to 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.
Equals () and hashcode () are both from Java. Lang. Object. Of course you can rewrite them.

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 an agreement. If you do not do this, it will not be wrong.

V. hashcode
In general applications, you do not need to understand the usage of hashcode. However, when using hashmap, hashset, and other collection classes, pay attention to the hashcode.

You want to use the key of an object to get the value of hashmap. The working method of hashmap is,
Use the hashcode of the object you passed in to find the address in the memory,
After finding the address, use the equals method to compare whether the content in the address is the same as that you put in.

so here we need to match two parts, hashcode and equals.
however, if you use a new object as the key to get the value, you will never get the result,
because every time a new object is created, the hashcode of this object is always different, so we need to rewrite the hashcode.
you can make your hashcode a constant in the object, in this way, you can always find the key address through the hashcode of your object.
then you need to rewrite your equals method so that the content in the memory is equal...

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.