The difference between equals and = = in Java (GO)

Source: Internet
Author: User

The difference between equals and = = in Java
A value type is a stack stored in memory (hereafter referred to as a stack), whereas a variable of a reference type is simply the address of a reference-type variable stored in the stack, which itself is stored in the heap.
The = = Operation compares the values of two variables for equality, and for a reference variable represents whether the two variables are stored in the same address in the heap, that is, whether the contents of the stack are the same.
Whether the two variables represented by the equals operation are references to the same object, that is, whether the contents of the heap are the same.
= = compares the addresses of 2 objects, while equals compares the contents of 2 objects. Obviously, when equals is true, = = is not necessarily true; one, equals in string and = = 1,
public class TestString {
public static void Main (string[] args) {String S1 = "Monday";      String s2 = "Monday"; } }
How many objects are there in this procedure? Check it out, change it a little bit. Program 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 refer to the same String object-"Monday"! 2.
A little change to the program, there will be more strange discovery: 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))


2014 second half of the teacher qualification examination for the middle school teacher Qualification Test Primary teacher Qualification Examination Preschool Teacher Qualification Examination Teacher Qualification Certificate interview


System.out.println ("S1 equals S2"); Else
System.out.println ("S1 not equals S2"); } }
We will S2 to create the program output with the new operator: S1! = s2 S1 equals s2
Description: S1 S2 cited two "Monday" string objects respectively
3. String buffer pool
It turns out that a string buffer pool is created when the program runs
When using S2 = "Monday" Such expression is to create a string, the program first in this string buffer pool to find the same value of the object, in the first program, S1 was put into the pool, so when the S2 was created, the program found a S1 with the same value will s2 reference S1 the referenced Object "Monday"
In the second procedure, the new operator was used, and he understood the telling program: "I want a new one!" Don't be old! "So a new" Monday "Sting object is created in memory. Their values are the same, but the locations are different and one swims in the pool
A rest on the shore. Alas, it is a waste of resources, obviously the same must be divided into what? 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"); } }
This time join: 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 also the string "abc", which looks as if this method is of little use. But in fact, it made a little gesture:
Check if there is an "ABC" string in the string pool, return the string in the pool if it exists, and if it does not, the method adds "ABC" to the string pool and returns its reference. )
A better approach:
Put all the strings intern () to the buffer pool. It's best to do this when you use new, string s2 = new String ("Monday"). Intern (); Then you can compare the values of two strings with = =.
Ii. equals and = = in simple data types and encapsulation classes
Java provides a wrapper class for each simple data type, and each base data type can be encapsulated into an object type. In addition to int (Integer) and char (Character), the remaining type is capitalized as a wrapper class type name. Double (double), float (float), long (long), short (short), Byte (Byte), Boolean (Boolean).
using int and integer as an example, 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 the encapsulated class of int, the default value is null, and 3.int and integer can represent a certain value;
4.int and integer cannot be interoperable 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 set up, very simple, all know
A1==b1 this is not tenable. The value of the expression is false, and they are different data types (true in version jdk1.5 or above)
B1==b2 This is also not tenable. The value of the expression is false, although it is the same data type, but they are two objects, = = compares the addresses of 2 objects, their addresses are not equal, the content is equal to 1;
B1.equals (B2) ==true This is true, the value of the expression is. The same data type, two objects, the address is different, the content is the same, quals comparison is the content of 2 objects, so set up.
(A.equals (b), because equals compares two objects, a, B cannot be a base data type, or a compilation error occurs.) (in jdk1.5 and above, B can be the basic data type, a cannot) the same way, other encapsulation classes and basic types are the same. The difference between equals and = = in Java
= = compares the addresses of 2 objects, while equals compares the contents of 2 objects.
In versions above jdk1.5, the base and wrapper classes can be converted automatically, similar to string-type objects and strings constants.         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 (i  4) = true I2 = = I4 = False I2.equals (i4) = true i = = I2 = True I1.equals (i) = true i = = I4 = True I4.equals (i) = True
Third, other classes how to use equals and = =
Most of the classes in the API rewrite the Equals method, and the class that is not rewritten is usually written by itself.
If you define a class, compare custom classes with equals and = = is the same, is the comparison handle address, because the custom class is inherited from object, and the equals in object is used = = To achieve, you can see the source code.



Iv. What is the relationship between equals and Hashcode in Java
Just to maintain a regular contract for the Hashcode method, the hashcode of the two objects compared with equals is required. Equals () and hashcode () are all from java.lang.Object. Of course you can rewrite.
such as A.equals (b). Returns true only if the memory address of a is equal. Of course, such as String class has already rewritten this method, the comparison is no longer the memory address.
The value of Hashcode () is also associated with memory addresses. Therefore, hashcode are equal only if the memory addresses are equal.
Also many classes override this method, or string for 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 two objects that are returned as true are compared with equals, and that their hashcode are the same.
So the general rewrite of equals will rewrite Hashcode (). Of course, this is equivalent to a contract, a protocol. You don't do it right.
Wu, Hashcode
In general applications you do not need to understand the use of hashcode, but when you use Hashmap,hashset and other sets of classes to pay attention to the hashcode.
You want to take HashMap's Value,hashmap by an object key. The way to work is to find the address in memory through the hashcode of your incoming object,
When this address is found, then the Equals method is used to compare whether the contents of this address are the same as the one you put in, and the value is taken out.
So here's to match 2 parts, hashcode and equals
But if you say you new object as key to get value is never the result,
Because every time new an object, the hashcode of this object is always different, so we're going to rewrite hashcode,
You can make your hashcode a constant in object so that you can always find the address of the key through the hashcode of your object, and then you rewrite your Equals method to make the contents of the memory equal ...

The difference between equals and = = in Java (GO)

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.