In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how to understand the String and packaging class of Java". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "how to understand the String and packaging class of Java"!
String connection @ Testpublic void contact () {/ / 1 connection String S1 = "a"; String S2 = "a"; String S3 = "a" + S2; String S4 = "a" + "a"; String S5 = S1 + S2; / / when the expression is constant, the runtime is calculated when the compilation time is complete and / / the expression has variables, so the address is different System.out.println (S3 = = S4) / / f System.out.println (S3 = = S5); / / f System.out.println (S4 = = "aa"); / / t} internpublic void intern of type String () {/ / 2:string intern usage / / S1 is the basic type, compare values. S2 is a string instance. Comparing instance address / / string types with the equals method will only compare the value String S1 = "a"; String S2 = new String ("a"); / / when calling intern, if the character in S2 is not in the constant pool, join the constant pool and return the constant reference String S3 = s2.intern (); System.out.println (S1 = = S2); System.out.println (S1 = = S3) } equals method of equals// string of type String / / public boolean equals (Object anObject) {/ / if (this = = anObject) {/ / return true;//} / / if (anObject instanceof String) {/ / String anotherString = (String) anObject;// int n = value.length / / if (n = = anotherString.value.length) {/ / char v1 [] = value;// char v2 [] = anotherString.value;// int I = 0 / / while (nMel -! = 0) {/ / if (v1 [I]! = v2 [I]) / / return false;// iTunes / / return true / /} / return false;//} StringBuffer and Stringbuilder
The bottom layer is the variable character array value that inherits the parent class
/ * The value is used for character storage. * / char [] value; initialization capacity is 16 characters Constructs a string builder with no characters init and an * initial capacity of 16 characters. * / public StringBuilder () {super (16);} the append methods of both classes are from the parent AbstractStringBuilder method public AbstractStringBuilder append (String str) {if (str = = null) return appendNull (); int len = str.length (); ensureCapacityInternal (count + len); str.getChars (0, len, value, count); count + = len; return this;} @ Overridepublic StringBuilder append (String str) {super.append (str); return this } @ Overridepublic synchronized StringBuffer append (String str) {toStringCache = null; super.append (str); return this;} appendStringbuffer adds the synchronized keyword to most operations involving string modification to ensure thread safety and is inefficient. When the String type uses the + operator such as String a = "a" a = a + a;, it actually encapsulates an into stringbuilder, calls the append method and then returns it with tostring, so when a large number of string additions are used, a large number of stringbuilder instances are generated, which is very wasteful, and stringbuilder should be used instead of string. Capacity expansion # Note: a function ensureCapacityInternal (count + len) is called in the append method. This method calculates whether the space after append is sufficient. If it is insufficient, you need to expand public void ensureCapacity (int minimumCapacity) {if (minimumCapacity > 0) ensureCapacityInternal (minimumCapacity). } private void ensureCapacityInternal (int minimumCapacity) {/ / overflow-conscious code if (minimumCapacity-value.length > 0) {value = Arrays.copyOf (value, newCapacity (minimumCapacity));}} if the length of the new string is greater than the length of the value array, the length after expansion is generally twice the original length + 2 If the expanded length exceeds the maximum array length MAX_ARRAY_SIZE supported by jvm. Consider two cases where if the length of the new string exceeds the int maximum, an exception is thrown, otherwise the maximum length of the array is directly used as the length of the new array. Private int hugeCapacity (int minCapacity) {if (Integer.MAX_VALUE-minCapacity)
< 0) { // overflow throw new OutOfMemoryError(); } return (minCapacity >MAX_ARRAY_SIZE)? MinCapacity: MAX_ARRAY_SIZE;} delete these two types of deletion operations: both call the delete method of the parent class to delete public AbstractStringBuilder delete (int start, int end) {if (start)
< 0) throw new StringIndexOutOfBoundsException(start); if (end >Count) end = count; if (start > end) throw new StringIndexOutOfBoundsException (); int len = end-start; if (len > 0) {System.arraycopy (value, start+len, value, start, count-end); count- = len;} return this;} is actually re-copying the remaining characters to the character array value.
System.arraycopy is used to copy the array here, and the speed is relatively fast.
The system.arraycopy approach turns to self-knowledge: on the mainstream high-performance JVM (HotSpot VM, IBM J9 VM, JRocket, and so on), System.arraycopy () can be considered reliable and efficient when copying arrays-if you find that it is not efficient enough, please report performance bug, which will certainly be improved soon. The java.lang.System.arraycopy () method is declared as a native method in the Java code. So the most na ï ve implementation is through JNI calling the native code in JVM. The immutability of String
About the immutability of String, here's a good answer.
What is immutable?
String immutability is very simple, as shown in the following figure, an existing string "abcd" is assigned to "abcedl" for the second time, not to modify the data on the original memory address, but to repoint to a new object, new address.
Cdn.xitu.io/2019/4/6/169f1fe50dacd299?w=720&h=233&f=jpeg&s=13305 ">
Why is String not changeable?
After opening the JDK source code, the first three lines of the java.lang.String class are written as follows:
Public final class String implements java.io.Serializable, Comparable, CharSequence {/ * * String are essentially char arrays. And use the final keyword to modify. * / private final char value [];...}
First of all, the String class is modified with the final keyword, which means that String is not inheritable. See below that the main member field value of the String class is an char [] array and is decorated with final.
Final-decorated fields cannot be changed after they are created. Some people think this is the end of the story, but it is not. Because although value is immutable, only the reference address of value is immutable. The fact that you can't block the Array array is variable.
The data structure of Array is shown in the following figure.
In other words, the Array variable is just a reference on stack, and the ontology structure of the array is in the heap heap.
The value in the String class is decorated with final, only that the reference address called value in stack is immutable. It is not said that the data of array itself in the heap is immutable. Look at the following example
Final int [] value= {1jie 2J 3}; int [] another= {4J 5J 6}; value=another; / / compiler error, final immutable value decorated with final, the compiler does not allow me to point value to another address in the heap area. But if I just hit on the array elements, I'll do it in a minute. Final int [] value= {1jc2jol 3}; value [2] = 100; / / at this time the array is already {1Jet 2100} so String is immutable, the key is because of the engineers from SUN. In all the subsequent String methods, it is careful not to move the elements in the Array and not to expose the internal member fields. In the sentence private final char value [], the private access of private is more important than that of final. And the designer is also very careful to set the entire String so that final forbids inheritance to avoid being destroyed by others' inheritance. So String is the immutable key to all the underlying implementations, not a final. The test is the engineer's ability to construct data types and encapsulate data. What are the benefits of immutability?
The simplest reason is for safety. Take a look at the following scenario (the comment response example is not clear enough, now write it in full), a function appendStr () returns after adding a paragraph "bbb" to the immutable String parameter. AppendSb () is responsible for adding "bbb" to the variable StringBuilder.
Summarize the immutability of the following String.
First of all, the final-decorated class only guarantees that it cannot be inherited, and the address of the object of this class in heap memory will not be changed.
2 but the reference that holds the String object itself can be changed, for example, it can point to other objects.
The final-modified char array ensures that the reference of the char array is immutable. However, the value can be modified by char [0] ='a'. However, String does not provide methods to do this internally, so the immutability of String is also based on code encapsulation and access control.
For instance
Final class Fi {int a; final int b = 0; Integer s;} final char [] a = {'a'}; final int [] b = {1}; @ Testpublic void final modifier class () {/ / reference is not modified by final, so it is mutable. / / final only modifies the Fi type, that is, the memory address of the object instantiated by Fi is immutable in the heap. Although the memory address is immutable, the internal data can be changed. Fi f = new Fi (); f.a = 1; System.out.println (f); f.a = 2; System.out.println (f); / / changing the value in the instance does not change the memory address. Fi ff = f; / / Let the reference point to the new Fi object, which is held by the new reference ff. The change in the direction of the reference does not change the address of the original object f = new Fi (); System.out.println (f); System.out.println (ff);} the modification of f. A here can be understood as an operation such as char [0] ='a'. Only change the data value, not the memory value. At this point, I believe you have a deeper understanding of "how to understand the String and packaging class of Java". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.