Part 5 Common Java Classes (1) String Related Classes

Part 5 Commonly Used Java Classes (1) String Related Classes

1. String class

(注意:在Java中我们可以这样声明一个字符串String str = 'hello';但是,String并不是像int、char、double等的基本数据类型,它是Java中提供的类,可以使用字面量的方式声明,也可以使用实例化对象的方式:String str = new String('hello');)

1.Characteristics of String

  • Immutability: String objects are immutable. If you look at the JDK documentation, you will find that every method in the String class that seems to modify the String value actually creates a new String object to contain the modified string. content. The original String object remains unchanged.《Java编程思想(第4版)》

Insert image description here

  • The embodiment of immutable objects: reassigning a string or concatenating a string (including calling the repalce() method) requires rewriting the assigned memory area, and cannot be modified by the original value;

2.String storage

(1) Comparison of String instantiation methods

Insert image description here

  • The string constants we declare will be stored in the string constant pool, and non-constants (objects) are stored in the heap.
  • The method of declaring and assigning strings through literals (different from new): directly points to the corresponding string address stored in the string constant pool.
  • Through new: the String object points to the address in the heap, which stores the address of the corresponding string in the string constant pool.
  • Strings with the same content will not be stored in the string constant pool (for example: str1 and str2 both point to the same string)
(2) Comparison of String splicing methods

Insert image description here

  • Conclusion 1: The concatenation result of constants and constants is stored in the string constant pool, and there will be no constants with the same content in the constant pool.
  • Conclusion 2: The concatenation results of variables and other (variables/constants) are stored in the heap.
  • Conclusion 3: If the concatenated string calls the intern() method, the returned string is also stored in the constant pool.
    (和变量拼接就放在堆中,其他在字符串常量池中)

3. Common methods of String

method effect
int length( ) Returns the length of the string (the length of the value[ ] array value.length)
char charAt( int index ) Returns the character at index value (i.e. value[index])
boolean isEmpty( ) Determine whether it is an empty string
String toLowerCase( ) Using the default locale, convert all characters in String to lowercase characters
String toUpperCase( ) Using the default locale, convert all characters in String to uppercase characters
boolean equals( Object obj ) Compare string contents for consistency
boolean equalsIgnoreCase( String str ) Compare string contents for consistency (ignoring case)
String trim( ) Returns a string ignoring leading and trailing whitespace
String concat( String str ) Concatenates the specified string to the end of this string (equivalent to +)
int compareTo( String str ) Compare the sizes of two strings and return the length difference
String substring( int beginIndex ) Returns the substring intercepted from the specified index to the end
String substring( int beginIndex,int endIndex ) Returns the substring starting from the specified index and ending at the specified index (exclusive)
boolean endsWith( String suffix ) Determine whether the string ends with the specified suffix (string)
boolean startsWith( String prefix ) Determine whether the string ends with the specified prefix (string)
boolean startsWith( String prefix,int toffset ) Determine whether the substring of the string starting from the specified index starts with the specified prefix
boolean contains( CharSequence s ) Determine whether a string contains a specified char value sequence
int indexOf( String str ) Returns the index of the first occurrence of a string in the specified string
int indexOf( String str,int fromIndex ) Returns the index of the first occurrence of a string at the specified index in the specified string
int lastIndexOf( String str ) Returns the index of occurrence of string from the right in the specified string
int lastIndexOf( String str,int fromIndex ) Returns the index of the string starting from the right of the specified string to the specified index.
String replace( char oldChar,char newChar ) Returns the string obtained by replacing the original oldChar with newChar.
String replace( CharSequence target,CharSequence replacement ) Replaces all substrings of this string that match the literal target sequence with the specified literal replacement sequence.
String replaceAll( String regex,String replace ) Replace all strings matching the regular expression based on the specified string
String replaceFirst( String regex,String replace ) Replaces the first substring of the matching regular expression based on the specified string
boolean matches( String regex ) Determines whether a string matches a specified regular expression
String[ ] split( String regex ) Split string based on specified regular expression
String[ ] split( String regex,int limit ) Split the string according to the specified regular expression and place the last element beyond the limit

4.String conversion

(1) Convert string to basic data type and packaging class
method effect
Integer.parseInt( String str ) Convert string to integer
Integer.parseByte( String str ) 字符串转字节型
Integer.parseFloat( String str ) 字符串转浮点型
…… ……
(2)基本数据类型转字符串
方法 作用
valueOf( int n ) int型转字符串
valueOf( byte b ) 字节型转字符串
valueOf( float f ) 浮点型转字符串
…… ……
(3)字符数组char[ ]转字符串
String的构造器 作用
String( char [ ] ) 将字符数组转成字符串
String( char [ ],int offset,int length ) 将指定位置开始和长度的字符数组转成字符串
(4)字符串转字符数组char[ ]
方法 作用
toCharArray( ) 字符串转字符数组
getChars( int srcBegin,int srcEnd,char[] dst,int dstBegin ) 指定字符串转字符数组
(5)字节数组byte[ ]转字符串
String的构造器 作用
String( byte[ ] ) 使用默认字符集转换byte数组为字符串
String( byte[ ],int offset,int length ) 使用默认字符集转换byte数组的指定索引、长度为字符串
(6)字符串转字节数组
方法 作用
getBytes( ) 使用默认字符集转换将字符串为字符数组
getBytes( String charsetName ) 使用指定字符集转换将字符串为字符数组

二、StringBuffer类和StringBuilder类

上面所讲的String类是一个不可变的对象(不可变序列的字符串),接下来的StringBuffer和StringBuilder类均是可变的

1.String、StringBuffer和StringBuilder的区别

String:不可变的字符序列
StringBuffer:可变的字符序列,线程安全(方法均为synchronized声明的同步方法),但效率较低
StringBuilder:可变的字符序列,线程不安全,效率高(JDK 5.0新增)
(String、StringBuffer和StringBuilder底层都是使用byte[ ]数组来存储,而StringBuffer和StringBuilder是可变的,所以底层数组没有用final声明,而String类是不可变的,所以底层存储的数组用final声明private final byte[ ] value。PS:老版本JDK是char型数组)

2.StringBuffer和StringBuilder的底层实现

在使用String类时,我们操作字符串(对字符串重新赋值或字符串连接,包括调用repalce( )方法),不能通过底层原有的byte[] value数组进行修改,而是需要在内存中重新创建一个String对象,所以才说String类是一个不可变的对象;StringBuffer类和StringBuilder类与其不同,都是可变的对象,那么这两个类的底层是如何实现其的"可变"的呢?

(1) Capacity of array byte[ ] value

Insert image description here
Insert image description here
Insert image description here

(2) Code verification (1)

[Verification 1-1] Create a StringBuffer object initialized to a null character (empty parameter). The default capacity of the underlying byte[] value is 16.
[Verification 1-2] Create a StringBuffer object initialized as a string str (with parameters). The default capacity of the underlying byte[ ] value is str.length( )+16

import org.testng.annotations.Test;

public class StringTest {
    
    
    @Test
    public void test3(){
    
    
        StringBuffer strBuffer1 = new StringBuffer("");
        /**
         *【验证1-1】创建一个初始化为空字符的(空参)的StringBuffer对象,
         * 底层数组默认容量大小为16
        **/
        System.out.println("初始化为空字符串的长度:"+strBuffer1.length());//""长度0
        System.out.println("初始化为空字符串byte[] value的容量大小:"+strBuffer1.capacity());//16

        /**
         *【验证1-2】创建一个初始化为str字符串(带参)的StringBuffer对象,
         * 底层数组默认容量大小为str.length()+16 
        **/
        StringBuffer strBuffer2 = new StringBuffer("hello");
        System.out.println("初始化为指定字符串的长度:"+strBuffer2.length());//"hello"长度5
        System.out.println("初始化为指定字符串时byte[] value的容量大小:"+strBuffer2.capacity());//21
    }
}

Insert image description here

到了这里,如果调用strBuffer2.append('aaaaa')直到超出原初始化的长度21,数组即将越界,底层是如何实现其容量的扩容呢?

(3) Expansion of array byte[ ] value

Insert image description here

Insert image description here

Insert image description here

Insert image description here

(4) Code verification (2)

[Verification 2-1] By default, the expanded capacity of the underlying value array of StringBuffer is 2 times + 2.
[Verification 2-2] When the required capacity exceeds 2 times + 2 of the original array capacity, directly expand the capacity to the required capacity.

import org.testng.annotations.Test;

public class StringTest {
    
    
    @Test
    public void test3(){
    
    
        /**
         * 【验证2-1】默认情况下,StringBuffer底层value数组扩容后的容量为原来的2倍+2。
         * */
        StringBuffer stringBuffer = new StringBuffer();
        System.out.println("当前字符串长度:"+stringBuffer.length());//0
        System.out.println("当前value数组容量:"+stringBuffer.capacity());//16

        stringBuffer.append("HelloWorldHelloWorld");   //length = 20
        System.out.println("扩容字符串长度:"+stringBuffer.length());//20
        System.out.println("扩容后value数组容量:"+stringBuffer.capacity());//34
    }
    @Test
    public void test4(){
    
    
        /**
         * 【验证2-2】当需要的容量超过原数组容量的2倍+2,则直接扩容为所需容量。
         * */
        StringBuffer stringBuffer = new StringBuffer();
        System.out.println("当前字符串长度:"+stringBuffer.length());//0
        System.out.println("当前value数组容量:"+stringBuffer.capacity());//16

        stringBuffer.append("HelloWorldHelloWorldHelloWorldHelloWorld");   //length = 40
        System.out.println("扩容字符串长度:"+stringBuffer.length());//40
        System.out.println("扩容后value数组容量:"+stringBuffer.capacity());//40
    }
}

Insert image description here

3. Common methods of StringBuffer and StringBuilder

method effect
StringBuffer append(xxx) String concatenation (increased)
StringBuffer insert(int offset,xxx) Insert element at specified position (increment)
StringBuffer delete(int start,int end) Delete string elements (delete)
StringBuffer replace(int start,int end,String str) Modify the element at the specified position (change)
setCharAt(int n,char ch) Modify the element at the specified position (change)
char charAt(int n) Returns the element at the specified position (check)
StringBuffer reverse( ) Arrange strings in reverse order
...(Others are similar to String) ……
  • Iterate over array elements

    for(int i=0;i<stringBuffer.length();i++){
          
          
        System.out.print(stringBuffer.charAt(i));
    }
    

4.String, StringBuffer and StringBuilder efficiency

  • StringBuilder > StringBuffer > String
import org.testng.annotations.Test;

public class StringTest {
    
    
    @Test
    public void test6() {
    
    
        //初始设置
        long startTime = 0L;
        long endTime = 0L;
        String text = "";
        StringBuffer buffer = new StringBuffer("");
        StringBuilder builder = new StringBuilder("");
        //开始对比
        startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
    
    
            buffer.append(String.valueOf(i));
        }
        endTime = System.currentTimeMillis();
        System.out.println("StringBuffer的执行时间: " + (endTime - startTime));
        startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
    
    
            builder.append(String.valueOf(i));
        }
        endTime = System.currentTimeMillis();
        System.out.println("StringBuilder的执行时间: " + (endTime - startTime));
        startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
    
    
            text = text + i;
        }
        endTime = System.currentTimeMillis();
        System.out.println("String的执行时间: " + (endTime - startTime));
    }
}

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_54429787/article/details/128590315