Simple operation of StringBuffer in Java + a classic interview question

Source:
Disclaimer: If I violate anyone's rights, please contact me and I will delete it.
Welcome experts to spray me

The difference between StringBuffer and String

String is an immutable object, so every time the String type is changed, a new String object will be generated, and then the pointer will point to the new String object. Therefore, it is best not to use String for strings that frequently change content, because Every time an object is generated, it will have an impact on system performance, especially when there are too many unreferenced objects in the memory, the JVM GC will start to work and performance will decrease.

When using the StringBuffer class, every time you operate on the StringBuffer object itself, instead of generating a new object and changing the object reference. So it is recommended to use StringBuffer in most cases, especially when the string object changes frequently.

In some special cases, the string splicing of String objects is actually compiled into the splicing of StringBuffer objects by Java Compiler, so the speed of String objects is not slower than StringBuffer objects at these times

Inheritance of StringBuffer

Insert picture description here

StringBuffer 的 API

ConstructorInsert picture description here

length function and capacity function

Insert picture description here
length() is the number of elements:

   public synchronized int length() {
   //count是元素的个数
        return count;
    }

capacity:

   public synchronized int capacity() {
   //value是char[]类型,真正存储元素的地方
        return value.length;
    }

length is the length actually allocated to the StringBuffer, and capacity is the total capacity of the StringBuffer.

StringBuffer sb = newStringBuffer(); If the incoming is an integer, you can set the size of the capacity without changing the length of the length. The default capacity is 16

StringBuffer sb = newStringBuffer(10);

Sb.append("ab"); sb.length() is 2, sb.capacity() is 18;

StringBuffer sb = newStringBuffer(); sb.length() is 0, sb.capacity() is 16

charAt function

The following are similar functions:
Insert picture description here

getChars and setChar functions

getChars puts the chars between [srcBegin, srcEnd) in dst[dstBegin~):

    public synchronized void getChars(int srcBegin, int srcEnd, char[] dst,
                                      int dstBegin)
    {
        super.getChars(srcBegin, srcEnd, dst, dstBegin);
    }

setChar

    public synchronized void setCharAt(int index, char ch) {
        if ((index < 0) || (index >= count))
            throw new StringIndexOutOfBoundsException(index);
        toStringCache = null;
        value[index] = ch;
    }

append function

Insert picture description here

substring gets some functions

Insert picture description here

delete function

Insert picture description here

insert function

Insert picture description here

index bitwise search function

Insert picture description here

reverse function

Insert picture description here

    public synchronized StringBuffer reverse() {
        toStringCache = null;
        super.reverse();
        return this;
    }

toString to String function

   public synchronized String toString() {
        if (toStringCache == null) {
            toStringCache = Arrays.copyOfRange(value, 0, count);
        }
        return new String(toStringCache, true);
    }

Classic interview questions = examine the value transfer problems of int, String and StringBuffer

Source: http://blog.sina.com.cn/s/blog_50800ffd0102vvtu.html

public class ReferenceChangeValue {

	public static void change(int k1,String s1,StringBuffer sb1){

		k1 = 2;

		s1 = "a";

		//sb1 = new StringBuffer("C");​

		sb1.append("C");

	}

	public static void main(String[] args) {

		int k = 1;

		String s = "A";

		StringBuffer sb = new StringBuffer("B");

		change(k,s,sb);

		System.out.println("k = "+k+"  s = "+s+"  sb = "+sb);

	}

}

Result of the program:
K = S = A. 1 = the BC SB
// see, int type and value of type String variable not changed, the value of the variable type StringBuffer changed.

analysis:

  1. Java only has value transfer, int is the primitive type (PrimitiveType), the value is passed, String and StringBuffer are the class, ReferenceType (reference type)​, the reference of the object is passed.

  2. ​Int type value transfer. When a basic type of variable is passed as a parameter to a method, what the JAVA virtual machine does is to copy the value, and then pass the copied value to the method.

    ​​In the change() function, the k1 variable is a local variable. After the change() function is executed, the life cycle of k1 ends, and the memory address of k1 will be recycled by the GC. The change of k1 will not affect the change of k value. The k in the k1 and main() functions are only equal in value, they are different variables, and the memory addresses they point to are different.

  3. String and StringBuffer and other reference types (ReferenceType, there are three types: class, interface, and array) value transfer, the JAVA virtual machine copies the reference held by this variable, and then passes it to the JAVA virtual machine to create a local method Variables, so that the two variables point to the same object.

    When an object or reference type variable is passed as a parameter, it is also passed by value. This value is the reference of the object. Therefore, there is only value passing in JAVA, not reference passing.

    ​So, the JAVA virtual machine transfers the information of the object's storage address in the heap to the formal parameter variable in the change() function, so that the actual parameter variable in the main() function and the formal parameter variable in the change() function all point to the same An address, however, is still two independent variables, and the only association is to point to an address in the same heap.

    Next, analyze the program, ​String variables s and s1 point to the address of the variable s in the heap, s1 = "a" in the change() function; the effect is only to change the local variable s1 (stored in the stack, scope Limited to the point of the change() function), it points to the memory address of "a", and the point of the s variable in the main() function has not changed, so after the change() function is executed, the s1 variable is destroyed, and the value of s is not affected. Similarly, if you replace sb1.append("C"); in the program with sb1 = new StringBuffer("C");​ the result of the operation is sb = B, the value of the StringBuffer variable sb will not change, because The pointing change of the local variable sb1 will not affect the pointing of sb.

    So, ​sb1.append("C"); Why can this sentence change the values ​​of sb1 and sb? That's because sb1 points to the address of sb. Executing the append() method will change the value attribute value of the StringBuffer object stored in the sb address, which is different from changing the point of local variables, which changes the attribute value of the object pointed to by the local variable (object reference). .

Guess you like

Origin blog.csdn.net/qq_45531729/article/details/112253528