String detention string. Intern

Source: Internet
Author: User
String S1 =   " Mytest " ;
String S2 =   New Stringbuilder (). append ( " My " ). Append ( " Test " ). Tostring ();
String S3 =   String . Intern (S2 );
Console. writeline (object) S2 = (Object) S1 ); // Different references.
Console. writeline (object) S3 = (Object) S1 ); // The same reference.

 

Intern
[In bytes t records: N] V. detention, house arrest N. Intern

 

The Common Language Runtime library stores strings by maintaining a table calledDetention pool, It containsProgramA reference to each unique string declared or created programmatically. Therefore, there is only one instance of a string with a specific value in the system.

For example, if the same string is assigned to several variables, the runtime will retrieve the same reference to the string from the detention pool and allocate it to each variable.

The intern method uses the detention pool to searchStr
A string with equal values. If such a string exists, it is referenced in the detention pool. If not, add a pair to the detention poolStr
And then return the reference.

In the following C # example, the string S1 with the value of "mytest" is reserved because it is a String constant in the program.

Class to generate a new String object with the same value as S1. References to this string are assigned to S2.

The intern method searches for strings with the same value as S2. Because such a string exists, this method returns the same reference allocated to S1, and then assigns the reference to S3.

The comparison results of referencing S1 and S2 are not equal because they reference different objects, and the comparison results of referencing S1 and S3 are equal, because they reference the same string.

 

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.