The difference between equals and = = in Java

Source: Internet
Author: User

Reprinted from: http://new-fighter.iteye.com/blog/1634786

The difference value type of equals and = = in Java is a stack stored in memory (the stack), whereas a variable of a reference type is simply the address of the reference type variable stored in the stack, and itself 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;
equals and = = in a string

Java code
    1. 1.
    2. Public class TestString {
    3. public static void Main (string[] args) {
    4. String S1 = "Monday";
    5. String s2 = "Monday";
    6. }
    7. }

How many objects are there in this procedure?
Check it out, change the program a little bit.

Java code
  1. Public class TestString {
  2. public static void Main (string[] args) {
  3. String S1 = "Monday";
  4. String s2 = "Monday";
  5. if (S1 = = s2)
  6. System.out.println ("S1 = = s2");
  7. Else
  8. System.out.println ("S1! = s2");
  9. }
  10. }

Compile and run the program, output: S1 = = S2
Description: S1 and S2 refer to the same String object-"Monday"!

2.
A little more change to the program, there will be more strange discovery:

Java code
  1. Public class TestString {
  2. public static void Main (string[] args) {
  3. String S1 = "Monday";
  4. String s2 = new String ("Monday");
  5. if (S1 = = s2)
  6. System.out.println ("S1 = = s2");
  7. Else
  8. System.out.println ("S1! = s2");
  9. if (s1.equals (S2))
  10. System.out.println ("S1 equals S2");
  11. Else
  12. System.out.println ("S1 not equals S2");
  13. }
  14. }

We will create the S2 with the new operator
Program output:
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", the expression is to create a string, the program will first
In this string buffer pool to find objects of the same value, in the first program, S1 was first
is placed in the pool, so when S2 is created, the program finds the S1 with the same value
S2 refers to the object referenced by S1 "Monday"
In the second procedure, the new operator is used, and he knows the telling program:
"I want a new one!" Don't be old! "So a new" Monday "Sting object was created
Built 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.
To change the program again:

Java code
  1. Public class TestString {
  2. public static void Main (string[] args) {
  3. String S1 = "Monday";
  4. String s2 = new String ("Monday");
  5. S2 = S2.intern ();
  6. if (S1 = = s2)
  7. System.out.println ("S1 = = s2");
  8. Else
  9. System.out.println ("S1! = s2");
  10. if (s1.equals (S2))
  11. System.out.println ("S1 equals S2");
  12. Else
  13. System.out.println ("S1 not equals S2");
  14. }
  15. }

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).

take int and integer as an example to illustrate
The differences between int and Integer in Java are 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;
Both 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 base data type, a cannot)
Similarly, 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.

Java code
  1. Integer i1 = 123;
  2. Integer i2 = 123;
  3. int i = 123;
  4. Integer i3 = new Integer (123);
  5. Integer i4 = new Integer (123);
  6. System.out.println ("I1 = = I2 =" + (I1 = = i2));
  7. System.out.println ("i1.equals (I2) =" + (I1.equals (I2)));
  8. System.out.println ();
  9. System.out.println ("i3 = = I4 =" + (i3 = = i4));
  10. System.out.println ("i3.equals (i4) =" + (I3.equals (i4)));
  11. System.out.println ();
  12. System.out.println ("i2 = = I4 =" + (I2 = = i4));
  13. System.out.println ("i2.equals (i4) =" + (I2.equals (i4)));
  14. System.out.println ();
  15. System.out.println ("i = = I2 =" + (i = = i2));
  16. System.out.println ("i1.equals (i) =" + (i1.equals (i)));
  17. System.out.println ();
  18. System.out.println ("i = = I4 =" + (i = = i4));
  19. System.out.println ("i4.equals (i) =" + (i4.equals (i)));
  20. ------------------------------
  21. I1 = = I2 = true
  22. I1.equals (I2) = true
  23. i3 = = I4 = false
  24. I3.equals (i4) = true
  25. I2 = = I4 = false
  26. I2.equals (i4) = true
  27. i = = I2 = true
  28. I1.equals (i) = true
  29. i = = I4 = true
  30. 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 yourself, comparing custom classes with equals and = = is the same as comparing handle addresses,
Since the custom class is inherited from object, and equals in object is implemented with = =, 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.

There are also many classes that rewrite this method, or string for example:

Java code
  1. public int Hashcode () {
  2. int h = hash;
  3. if (h = = 0) {
  4. int off = offset;
  5. char val[] = value;
  6. int len = count;
  7. For (int i = 0; i < len; i++) {
  8. H = 31*h + val[off++];
  9. }
  10. hash = h;
  11. }
  12. return h;
  13. }

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 get HashMap's Value,hashmap by using an object key.
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 key through the hashcode of your object,
Then you have to rewrite your equals method so that the contents in memory are equal ...

The difference between equals and = = in Java

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.