7.4.4 String object problem, 7.4.4string object

Source: Internet
Author: User

7.4.4 String object problem, 7.4.4string object

String is the first class to be used frequently in Java. In the past, at least every month related posts were posted on the CSDN Forum, discussing = and equals ().

This section describes the content of this part.An important correction.

String text is widely used in programs. String textReference, Pointing to a String object. For example, a String object pointed to by "baby ",The data stored in the object mainly includes a char [] reference and three int values..

String detention

To effectively use the heap and accelerate the string processing efficiency (replace equals (Object) Comparison with =), multiple languages such as Java, C #, and Python supportString detention/concentration camp (string interning) TechnologyThat is, for each different string valueSave only one copy(The premise is that it must beUnchanged object).

Two detention methods in Java:

The compiler analyzes all the String text and constant expressions (such as "ba" + "by", "ba" + 3 + 2) in a class, obtain the result of a constant expression-String text, and then justDifferentString indicates the CONSTANT_String_info items of the class file (the same is true ). When a class is loaded, reference CONSTANT_Utf8_info according to its symbol, extract the characters in binary representation, create a String object in the "heap", and register the object reference in a HashMap.

A collection of all String objects registered in HashMap, which is sometimes called a string interning pool ). The HashMap resides inMethod Area, AndThe string pool is in the heap.(Note: Just as Java does not allocate object space in the stack, it only has a logical meaning ).

Package jvm. internedStrings; public class OnlyOneCopy {static String str1 = "abc"; String str2 = "a" + "bc"; public void foo () {String str3 = "a" + "B" + 'C'; // 'C' is not "c" System. out. println (str1 = str3 );}}

InLoadOnlyOneCopy, JVM creates a String object according to the CONSTANT_String_info item in the constant pool of the class file. Because the compiler automatically supports the String detention technology, the reference "abc" of the String object just created is registered in HashMap and handed to an unknown variable (assumed as #2) for storage. In the initialization phase of the class, the static variable str1 is initialized, that is, the reference of #2 is assigned "abc" to str1. When an OnlyOneCopy object is created somewhere, its instance domain str2 is initialized, assign the value of #2 to str2. When a program calls the method foo (), assign the value of #2 to str3. 【Variables can be referenced in various locations.]


The final result is: The result can be determined through =.Str1, str2, and str3 point to the same object..

Note that if the concatenation operator of a string contains variables, the compiler cannot be smart enough to determine the value of the expression. For example, String str1 = "abc"; StringStr2 = str1 + "";

Str1 and str2 point to different objects.

To reduce the number of String copies, there are two methods to achieve this: modifying str1 with final; using the String intern () method, such as str2 = (str1 + ""). intern ().

Xxx. intern () means to use the equals (Object) method to determine whether there is an available reference in HashMap. If yes, the reference is used as the reference of xxx. If no, the value of xxx is registered in HashMap and the String object is included in the pool. Can the String object in the String pool be reclaimed by garbage collection? In modern JVM implementation, a String object can be recycled if it is not a compilation constant and is no longer referenced.

Character substring

The substring (int begin, intend) of the String class returns the substring object of the message receiving object in the range of [begin .. end), and the String object is not in custody.

We know that the String objectThe stored data mainly contains a char [] reference and several int values.. The cost of creating a substring object in JVM is very small, mainly in char [] char [] pointed to by variable v.

String str = "abc ...... 100,000 why ". substring );

When creating a substring object, you do not need to copy any characters. The substring shares an underlying char [] object with the original string object, the substring does not change several int member variables (offset, length, etc.) of the original String object.

InJava 7u6It was correct, but it was modified later. The reason is that str only needs one character, but the space of the entire char []-10 W length cannot be released.

//JDK 6String(int offset, int count, char value[]) {this.value = value;this.offset = offset;this.count = count;} public String substring(int beginIndex, int endIndex) {//check boundaryreturn  new String(offset + beginIndex, endIndex - beginIndex, value);}

//JDK 7public String(char value[], int offset, int count) {//check boundarythis.value = Arrays.copyOfRange(value, offset, offset + count);} public String substring(int beginIndex, int endIndex) {//check boundaryint subLen = endIndex - beginIndex;return new String(value, beginIndex, subLen);}

[Figure 7-10 substring object] is corrected.




Number of JAVA String objects

In fact, the upstairs are all correct, but the answer is not correct. In fact, the correct answer is four, not three.
First step
String s1 = "1234"; a 1234 object is created in the String pool, pointing to s1; // an object is created here.
Step 2
String s2 = "1234"; it is first found in the String pool. There is a 1234 object in the pool, pointing directly to s2; // The existing object is used here, so the object is not re-created. At present, an object is still created.
Part III
String s3 = new String ("5678"); two objects are created here. Do not think about it. There are two objects, not one. First, create a 5687 object in the String pool, then create a String object in the memory of the team, and assign the 5678 object to the String object // There are two pairs of images. Do not mislead the errors upstairs.
Public String (String original ){
This. value = original. value;
This. hash = original. hash;
}
This is a String construction method with parameters. You need to upload a String object to copy the value and hashcode, so there are two
Part 4
String s4 = new String ("5678"); find in the String pool, there are 5678 objects, create a New String object in the heap and then copy 5678 to the New String object // because there are 5678 in the String pool, you do not need to create a new one, so only one object is created here.

To sum up, the first step creates an object, the second step does not create an object, the third step creates two objects, and the fourth step creates an object 1 + 0 + 2 + 1 = 4; therefore, a total of four objects have been created.

Basic questions about String objects

String (String original)
Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string.
Initialize A New String object and ensure that it is consistent with the Character Sequence of the parameter. In fact, a new copy is created.
If you do not want to create two, you can directly create String s = "xyz"

So when do we need to create two? As follows:
String a = "123 ";
String B = new String ();
A = "456 ";
String c = B + a; // c = "123456"

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.