Java Learning (b) What is string comparison between using the Equals method and = =?

Source: Internet
Author: User

The difference between the Equals method used by string and = =

The difference between the Equals method and = =   First you know that string can be used as an object or as a base type. This refers to use as a basic type only refers to the use of methods, such as String s = "Hello", it is used as a primitive type int, such as int i = 1, and as an object to use, it means to create a new object by using the new keyword, such as String s = new String ("Hello"). But its internal action actually creates an object, which we'll talk about later.          Second, the comparison method for string objects needs to be understood. There are two concepts of comparison between objects in Java, and here is a string object: One is compared with "= =", which is a reference to a variable of two string types, that is, if two variables of type string, they refer to the same string object ( That point to the same heap of memory), the result of the "= =" Comparison is true. The other is to use the Equals () method of the object objects to compare, the string object inherits from object, and the Equals () method is overridden. When a two string object is compared through the Equals () method, it is actually a comparison of the string content that is encapsulated by a string object, that is, if the string content of the two string object is the same (including the same case), the Equals () Method will return True.   Now begins the concrete analysis of the creation of the string object:  1,//////////////////////////////////////////////////////////////////////// /string S1 = new String ("Hello"); String s2 = new String ("Hello");  system.out.println (S1 = = s2); System.out.println (s1.equals (S2));  The result of the above code snippet is: falsetrue         The result is very well understood, Two variables of type string S1 and S2 each created a new string object, each of which allocates a new, separate heap of memory for each object created, by using the New keyword. So when you pass"= =" to compare whether they refer to the same object and return False. When compared by the Equals () method, True is returned because the contents of the strings encapsulated by the two objects are identical.  2,//////////////////////////////////////////////////////////////////////////////////string s1 = new String (" Hello "); String s2 = s1; system.out.println (S1 = = s2); System.out.println (s1.equals (S2));  The result of the above code snippet is: truetrue         This result should be better understood, The variable s1 also creates a new string object through the New keyword, but here S2 does not create a new string object by using the New keyword, but instead directly assigns the S1 to S2, which assigns the S1 reference to S2, So the object referenced by S2 is actually the object referenced by S1. So, when comparing by "= =", returns TRUE. Since they refer to the same object, the Equals () method will certainly return true when compared, and the Equals () method is actually comparing itself to the same object.  3,//////////////////////////////////////////////////////////////////////////////string s1 = "Hello"; String s2 = "Hello";  system.out.println (S1 = = s2); System.out.println (s1.equals (S2));  The above code snippet is the result of: truetrue         Why? Let's analyze it. First of all, these two string objects are used as a base type instead of being created by the new keyword, so the virtual machine does not allocate a new memory heap for the two string objects, but instead finds them in a string buffer pool.          First look for S1 to see if there is an "H" in the string buffer poolEllo "A string object of the same value exists, at this point the string buffer Ikeuchi is empty, there is no string object of the same value exists, so the virtual opportunity in the string buffer pool to create this string object, the action is the new string (" Hello "); The reference to this string object is then assigned to S1.          Then for S2 to find if there is a string object with the same value as "Hello" in the string buffer, the virtual machine finds a string object with its same value. This string object is actually a string object created for S1. Now that an object of the same value is found, the virtual machine does not create a new string object for this purpose, but instead assigns a reference to the existing string object to S2 directly.          since S1 and S2 refer to the same string object, which means they are equal to themselves, both of these comparison methods return ture.          Here, the basic concepts of string objects should be understood. Now, let me summarize.:  is used for string as a base type:  1. If string is used as a base type, we consider this string object to be owned by the string buffer pool. 2. If a string is used as a base type and there is no string object with the same value specified in the string buffer pool, then the virtual machine creates a new string object for this purpose and holds it inside the string buffer pool. 3. If a string is used as a base type, and there is a string object with the same value as the string in the buffer pool, then the virtual machine will not create a new string object for this purpose, and return a reference to the existing string object directly.   used for string as an object:  1. If string is used as an object, the virtual machine creates a new string object that allocates a new heap of memory for this object, and it is not owned by the string buffer pool, which is independent.   After understanding the above content, please see the following code snippet: 4,/////////////////////////////////////////////////////////////////////////////string s1 = "Hello"; StrinG s2 = new String ("Hello");  system.out.println (S1 = = s2); System.out.println (s1.equals (S2));  The result of the above code snippet is: falsetrue         analysis based on the summary above. The first line uses string as a base type, so the object referenced by S1 is within the string buffer pool. And there is no string object of the same value in the string buffer pool exists, so the virtual opportunity creates a new string object for this, that is, "new string" ("Hello");. The second line uses string as an object, so the object referenced by S2 is not part of the string buffer, that is, it is independent. With the new keyword, the virtual opportunity creates a new string object for this, allocating a new heap of memory to it. Therefore, the result of the "= =" Comparison is false, because S1 and S2 do not refer to the same object, they are independent. The Equals () method returns True because the contents of the string that the two objects encapsulate are identical.          Now, I'm sure you've fully figured out what the string object is all about: But that's not the end, because the string object has a deeper application.          Here I will analyze the application of the Intern () method of the String object: The Intern () method returns the canonical notation of a string object, which is the same string as the contents of the string. But a string buffer pool from a unique string. This sounds a bit of a mouthful, in fact its mechanism is like the following code snippet:  string s = new String ("Hello"), S = S.intern ();  The code snippet above can be simply seen as the following code snippet:  string s = "Hello";         You must be starting to wonder again? Then you can look at the second code snippet first. The second snippet means that a reference to a string object of the same value is fetched from the string buffer pool to S. If a string object with the same value does not exist in the string buffer pool, a new Str is created for thising object. So what does the first piece of code mean? We know the object created by the new keyword, and the virtual opportunity allocates a new heap of memory for it. If you create objects of the same content in an ordinary way, the virtual machines will also allocate many new memory heaps, although their contents are identical. For a String object, if you create 10 consecutive string objects of the same content (new string ("Hello")), the virtual machine allocates 10 separate memory heaps for this purpose. Assuming that the string object is created with a very large strings content, assuming that a Stirng object encapsulates a 1M size string, then if we create 10 of these same string objects, we will waste 9M of memory space meaningless. We know that the string is the final class, which encapsulates a string constant, so the string object cannot be changed after its creation (string) value, and therefore the string object can be shared. So for the hypothesis that we have just mentioned, we create a string object of 10 identical content, in fact we only need to create a string object for this, and then be shared by other string variables. The only and simple way to implement this mechanism is to use the string buffer pool because there is no string object of the same content in the string buffer pool. The Intern () method is the way to use this mechanism. After calling the Intern () method on an instantiated string object, the virtual opportunity looks for a string object within the string buffer pool that has the same value as the string content encapsulated by this Stirng object. The reference is then assigned to the string type variable that references the original string object. If there is no string object in the string buffer pool that has the same value as the string content encapsulated by this string object, the virtual opportunity creates a new string object for this purpose and assigns its reference to the string type variable that references the original string object. This achieves the purpose of sharing the same string object, and the original string object created by the new keyword is discarded and reclaimed by the garbage collector. This not only reduces the use of memory consumption, improves performance, and is also more convenient for comparison of string objects, because the same string object will be shared, so to determine whether two string objects are the same, you only need to use "= =" to compare, and no longer use Equals () method to compare, this is not only easier to use, but also improves performance, because the Equals () method of the string object will disassemble the contents of the string, and then compare each, if the string content is very large, then this comparison action greatly reduces performance.         Speaking of which, you might be a little vague about the application, so let me give you a simple example to illustrate the concept:         Suppose there is a class that It has a method of logging messages that record messages from the user (assuming that the message content may be large, and that the repetition rate is high), and that the messages are recorded in a list in the order in which they are received. I think some friends will. Design:  import Java.util.*; public class Messages { arraylist Messages = new ArrayList ();  public void record (String msg) {Messages.add (msg);}  public List getmessages () {return messages;}}          This design is good? Suppose we repeat the same message to the record () method (the message comes from a different user, so you can treat each message as a new String ("...")), and the message content is large, then this design will greatly waste memory space, because the message list is recorded in the newly created, Separate string objects, although their contents are the same. So how can you optimize it, actually very simple, see the following optimized example:  import Java.util.*; public class Messages { arraylist Messages = new ArrayList ();  public void record (String msg) {Messages.add (Msg.intern ());}  public List getmessages () {return messages;}}          As you can see, Messages.add (msg) in the original record () method, the code snippet becomes Messages.add (Msg.intern ()); The Intern () method is called only for the MSG parameter, which allows for a shared mechanism for duplicate messages, which reduces memory consumption and improves performance.   This example is a bit farfetched, butThis is just to illustrate these concepts!   So far, the fog of the string object has been eliminated, and as long as you keep these concepts in mind, later complex string applications can be built on this basis for analysis.

Java Learning (b) What does string compare by using the Equals method and = = separately? (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.