4, Java common class I

object

The Object class is the root class of the class hierarchy. Each class uses Object as its superclass. Each class directly or indirectly inherits from the Object class.

Common methods in Object include:

public int hashCode() //Returns the hash code value of the object.
// Note: the hash value is a value calculated according to the hash algorithm. This value is related to the address value, but not the actual address value.

public final Class getClass() //Returns the runtime class of this Object

public String toString() //Returns a string representation of the object.

protected Object clone() //Create and return a copy of this object. This method can be overridden

protected void finalize() 
// This method is called by the object's garbage collector when the garbage collector determines that there are no more references to the object. Used for garbage collection, but when is uncertain.

1, equals() method

1. Equivalence relation

1. Reflexivity

x.equals(x); // true

II. Symmetry

x.equals(y) == y.equals(x); // true

3. Transitivity

if (x.equals(y) && y.equals(z))
    x.equals(z); // true;

4, Consistency

The equals () method is called multiple times, and the result remains unchanged

x.equals(y) == x.equals(y); // true

5. Comparison with null

Calling x.equals (null) on any object that is not null will result in false

x.equals(null); // false;

2. Equivalence and equality

2. Thread safety

3. Performance

Summary of the use of the three

  • For basic types, = = determines whether two values are equal. Basic types have no equals() method.
  • For reference types, = = determines whether two variables refer to the same object, while equals () determines whether the referenced object is equivalent.
    Integer x = new Integer(1);
    Integer y = new Integer(1);
    System.out.println(x.equals(y)); // true
    System.out.println(x == y);      // false
    

    3. Realization

  • Check whether it is a reference to the same object. If so, return true directly;
  • Check whether it is the same type. If not, return false directly;
  • Transform the Object object;
  • Determine whether each key field is equal.
    public class EqualExample {
    
        private int x;
        private int y;
        private int z;
    
        public EqualExample(int x, int y, int z) {
            this.x = x;
            this.y = y;
            this.z = z;
        }
    
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;  //Check whether it is a reference to the same object. If so, return true directly;
            if (o == null || getClass() != o.getClass()){
                //Check whether it is the same type. If not, return false directly
                return false;
            }
    
            // Transform Object object
            EqualExample that = (EqualExample) o;
    
            // Determine whether each key field is equal.
            if (x != that.x) return false;
            if (y != that.y) return false;
            return z == that.z;
        }
    }
    

    2, Hash code () method

    hashCode () returns a hash value, and equals () is used to determine whether two objects are equivalent. Two equivalent objects must have the same hash value, but two objects with the same hash value are not necessarily equivalent.

    When overriding the equals () method, you should always override the hashCode () method to ensure that the hash values of the two equivalent objects are also equal.

    In the following code, two equivalent objects are created and added to the HashSet. We want to treat the two objects as the same and add only one object to the collection. However, because EqualExample does not implement the hasCode () method, the hash values of the two objects are different, resulting in the addition of two equivalent objects to the collection.

    EqualExample e1 = new EqualExample(1, 1, 1);
    EqualExample e2 = new EqualExample(1, 1, 1);
    System.out.println(e1.equals(e2)); // true
    HashSet<EqualExample> set = new HashSet<>();
    set.add(e1);
    set.add(e2);
    System.out.println(set.size());   // 2
    

    The ideal hash function should be uniform, that is, unequal objects should be evenly distributed over all possible hash values. This requires the hash function to take into account the values of all fields. Each field can be regarded as a bit of r-ary, and then form an r-ary integer. R is generally taken as 31 because it is an odd prime number. If it is an even number, when multiplication overflow occurs, the information will be lost, because multiplying with 2 is equivalent to moving one bit to the left.

    A number multiplied by 31 can be converted into shift and subtraction: the compiler will automatically optimize this. 31*x == (x<<5)-x

    @Override
    public int hashCode() {
        int result = 17;
        result = 31 * result + x;
        result = 31 * result + y;
        result = 31 * result + z;
        return result;
    }
    

    *Understand: Alt+Insert in IDEA can quickly generate hashCode () and equals () methods.

    3, toString() method

    Default return ToStringExample@4554617c In this form, the value after @ is the unsigned hexadecimal representation of hash code.

    public class ToStringExample {
    
        private int number;
    
        public ToStringExample(int number) {
            this.number = number;
        }
    }
    
    ToStringExample example = new ToStringExample(123);
    System.out.println(example.toString());
    
    ToStringExample@4554617c
    

    4, clone() method

    1. Clonable

    Clone () is the {protected method of Object. It is not public. If a class does not explicitly override clone (), other classes cannot directly call the clone () method of the class instance.

    public class CloneExample {
        private int a;
        private int b;
    }
    
    CloneExample e1 = new CloneExample();
    // CloneExample e2 = e1.clone(); 
    // 'clone()' has protected access in 'java.lang.Object'
    

    Overriding clone() yields the following implementation:

    public class CloneExample {
        private int a;
        private int b;
    
        // CloneExample inherits Object by default
        @Override
        public CloneExample clone() throws CloneNotSupportedException {
            return (CloneExample)super.clone();
        }
    }
    
    CloneExample e1 = new CloneExample();
    try {
        CloneExample e2 = e1.clone();
    } catch (CloneNotSupportedException e) {
        e.printStackTrace();
    }
    
    java.lang.CloneNotSupportedException: CloneExample
    

    CloneNotSupportedException is thrown above because CloneExample does not implement the clonable interface.

    It should be noted that the clone () method is not a method of the clonable interface, but a protected method of Object.

    The clonable interface only stipulates that if a class does not implement the clonable interface and calls the clone () method, it will throw clonnotsupportedexception.

    public class CloneExample implements Cloneable {
        private int a;
        private int b;
    
        @Override
        public Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
    }
    

    2. Light copy

    The reference type of the copy object and the original object refer to the same object.

    public class ShallowCloneExample implements Cloneable {
    
        private int[] arr;
    
        public ShallowCloneExample() {
            arr = new int[10];
            for (int i = 0; i < arr.length; i++) {
                arr[i] = i;
            }
        }
    
        public void set(int index, int value) {
            arr[index] = value;
        }
    
        public int get(int index) {
            return arr[index];
        }
    
        @Override
        protected ShallowCloneExample clone() throws CloneNotSupportedException {
            return (ShallowCloneExample) super.clone();
        }
    }
    
    // The reference type of the copy object and the original object refer to the same object.
    ShallowCloneExample e1 = new ShallowCloneExample();
    ShallowCloneExample e2 = null;
    try {
        e2 = e1.clone();
    } catch (CloneNotSupportedException e) {
        e.printStackTrace();
    }
    e1.set(2, 222);
    System.out.println(e1.get(2)); // 222
    System.out.println(e2.get(2)); // 222
    

    3. Deep copy

    The reference types of the copied object and the original object refer to different objects.

    public class DeepCloneExample implements Cloneable {
    
        private int[] arr;
    
        public DeepCloneExample() {
            arr = new int[10];
            for (int i = 0; i < arr.length; i++) {
                arr[i] = i;
            }
        }
    
        public void set(int index, int value) {
            arr[index] = value;
        }
    
        public int get(int index) {
            return arr[index];
        }
    
        @Override
        protected DeepCloneExample clone() throws CloneNotSupportedException {
            DeepCloneExample result = (DeepCloneExample) super.clone();
            // create new object
            result.arr = new int[arr.length];
            for (int i = 0; i < arr.length; i++) {
                result.arr[i] = arr[i];
            }
            return result;
        }
    }
    
    DeepCloneExample e1 = new DeepCloneExample();
    DeepCloneExample e2 = null;
    try {
        e2 = e1.clone();
    } catch (CloneNotSupportedException e) {
        e.printStackTrace();
    }
    e1.set(2, 222);
    System.out.println(e1.get(2)); // 222
    System.out.println(e2.get(2)); // 2
    

    4. Alternative to clone ()

    Using the clone () method to copy an object is complex and risky. It will throw exceptions and require type conversion. As mentioned in the Effective Java book, it's better not to use clone (). You can use copy constructor or copy factory to copy an object.

    public class CloneConstructorExample {
    
        private int[] arr;
    
        public CloneConstructorExample() { //Constructor
            arr = new int[10];
            for (int i = 0; i < arr.length; i++) {
                arr[i] = i;
            }
        }
    
        public CloneConstructorExample(CloneConstructorExample original) { // copy constructor 
            arr = new int[original.arr.length];
            for (int i = 0; i < original.arr.length; i++) {
                arr[i] = original.arr[i];
            }
        }
    
        public void set(int index, int value) {
            arr[index] = value;
        }
    
        public int get(int index) {
            return arr[index];
        }
    }
    
    CloneConstructorExample e1 = new CloneConstructorExample();
    CloneConstructorExample e2 = new CloneConstructorExample(e1);
    e1.set(2, 222);
    System.out.println(e1.get(2)); // 222
    System.out.println(e2.get(2)); // 2
    

    character string

    String is declared final, so it cannot be inherited.

    Internally, char array is used to store data, which is declared as final, which means that value array cannot refer to other arrays after initialization. And there is no method to change the value array inside the String, so it can ensure that the String is immutable.

    public final class String
        implements java.io.Serializable, Comparable<String>, CharSequence {
        /** The value is used for character storage. */
        private final char value[];
    

    1, Construction method

    public String() //Empty structure
    
    public String(byte[] bytes) //Convert string to byte array
    
    public String(byte[] bytes,int index,int length) //Converts a part of a byte array into a string
    
    public String(char[] value) //Convert character array to string
    
    public String(char[] value,int index,int count) //Convert a part of the character array into a string, and the third parameter represents the number
    
    public String(String original) //Convert string constant value to string
    

    Use example:

    public class StringDemo {
        public static void main(String[] args) {
            //public String(): empty structure
            String s=new String();
            System.out.println("s:"+s);
            System.out.println("s.length="+s.length());
            System.out.println("-----------------------");
    
            //public String(byte[] bytes): converts a byte array into a string
            byte[] bys={97,98,99,100,101};
    
            String s2=new String(bys);
            System.out.println("s2:"+s2);
            System.out.println("s2.length="+s2.length());
            System.out.println("-----------------------");
    
            //public String(byte[] bytes,int index,int length): convert part of the byte array into a string
            String s3=new String(bys,0,3); //3 characters from position 0
            System.out.println("s3:"+s3);//s3:abc
            System.out.println("s3.length="+s3.length());//s3.length=3
            System.out.println("-----------------------");
    
    
            //public String(char[] value): convert the character array into a string
            char[] chs={'a','b','c','d','e'};
            String s4=new String(chs); //3 characters from position 0
            System.out.println("s4:"+s4);
            System.out.println("s4.length="+s4.length());
            System.out.println("-----------------------");
    
            //public String(char[] value,int index,int count): convert part of the character array into a string
            String s5=new String(chs,0,3); //3 characters from position 0
            System.out.println("s5:"+s5);
            System.out.println("s5.length="+s5.length());
            System.out.println("-----------------------");
    
            //public String(String original): convert the string constant value into a string
            String s6=new String("abcde");
            System.out.println("s6:"+s6);
            System.out.println("s6.length="+s6.length());
        }
    }
    

    Characteristics of string: once assigned, it cannot be changed

    public static void test() {
        String s = "hello";
        s += "world";
        System.out.println("s:" + s); // helloworld
    }
    

    Small exercise:

    public static void test2(){
        String s1 = new String("hello");
        String s2 = new String("hello");
        System.out.println(s1 == s2); // false
        System.out.println(s1.equals(s2)); // true
    
        String s3 = new String("hello");
        String s4 = "hello";
        System.out.println(s3 == s4); // false
        System.out.println(s3.equals(s4)); // true
    
        String s5 = "hello";
        String s6 = "hello";
        System.out.println(s5 == s6); // true
        System.out.println(s5.equals(s6)); // true
    }
    

    2, Judgment function

    boolean equals(Object obj) //Compare whether the contents of the string are the same, case sensitive
    
    boolean equalsIgnoreCase(String str) //Compare whether the contents of the string are the same, ignoring case
    
    boolean contains(String str) //Judge whether the large string contains the small string
    
    boolean startsWith(String str) //Determines whether a string begins with a specified string
    
    boolean endsWith(String str) //Determines whether a string ends with a specified string
    
    boolean isEmpty()// Judge whether the string is empty
    

    Note: the string content is empty and the string object is empty.

    String s = "";//The string content is empty
    String s = null;//The string object is empty
    

    Use example:

    public class StringDemo3 {
        public static void main(String[] args) {
            // Create string object
            String s1 = "helloworld";
            String s2 = "helloworld";
            String s3 = "HelloWorld";
    
            // boolean equals(Object obj): compare whether the contents of strings are the same, case sensitive
            System.out.println("equals:" + s1.equals(s2));//true
            System.out.println("equals:" + s1.equals(s3));//false
            System.out.println("-----------------------");
    
            // boolean equalsIgnoreCase(String str): compare whether the contents of strings are the same, ignoring case
            System.out.println("equals:" + s1.equalsIgnoreCase(s2));//true
            System.out.println("equals:" + s1.equalsIgnoreCase(s3));//true
            System.out.println("-----------------------");
    
            // boolean contains(String str): judge whether a large string contains a small string
            System.out.println("contains:" + s1.contains("hello"));//true
            System.out.println("contains:" + s1.contains("hw"));//false
            System.out.println("-----------------------");
    
            // boolean startsWith(String str): determines whether a string starts with a specified string
            System.out.println("startsWith:" + s1.startsWith("h"));//true
            System.out.println("startsWith:" + s1.startsWith("hello"));//true
            System.out.println("startsWith:" + s1.startsWith("world"));//false
            System.out.println("-----------------------");
    
            //boolean endsWith(String str): determines whether a string ends with a specified string
            System.out.println("startsWith:" + s1.endsWith("d"));//true
            System.out.println("startsWith:" + s1.endsWith("world"));//true
            System.out.println("startsWith:" + s1.endsWith("hello"));//false
            System.out.println("-----------------------");
    
            // boolean isEmpty(): judge whether the string is empty.
            System.out.println("isEmpty:" + s1.isEmpty());//false
    
            String s4 = ""; //The string content is empty
            String s5 = null;//The string object is empty
            System.out.println("isEmpty:" + s4.isEmpty());//true
            // NullPointerException
            // s5 objects do not exist, so methods cannot be called. Null pointer exception
            //System.out.println("isEmpty:" + s5.isEmpty());
        }
    }
    

    3, Get function

    int length() //Gets the length of the string.
    
    char charAt(int index) //Gets the character at the specified index position
    
    int indexOf(int ch) //Returns the index of the first occurrence of the specified character in this string. Why is the parameter int type here instead of char type? The reason is: 'a' and 97 can actually represent 'a'
    
    int indexOf(String str) //Returns the index of the specified string at the first occurrence in this string.
    
    int indexOf(int ch,int fromIndex) //Returns the index of the first occurrence of the specified character in this string from the specified position.
    
    int indexOf(String str,int fromIndex) //Returns the index of the specified string where it first appears after the specified position.
    
    String substring(int start) //Intercepts the string from the specified position, and defaults to the end.
    
    String substring(int start,int end) //Intercept the string from the specified position to the end of the specified position. Left closed right open
    

    Use example:

    public class StringDemo4 {
        public static void main(String[] args) {
            // Define a string object
            String s = "helloworld";
    
            // int length(): get the length of the string.
            System.out.println("s.length:" + s.length());//10
            System.out.println("----------------------");
    
            // char charAt(int index): gets the character of the specified index position
            System.out.println("charAt:" + s.charAt(7));//r
            System.out.println("----------------------");
    
            // int indexOf(int ch): returns the index of the first occurrence of the specified character in this string.
            System.out.println("indexOf:" + s.indexOf('l'));//2
            System.out.println("----------------------");
    
            // int indexOf(String str): returns the index of the first occurrence of the specified string in this string.
            System.out.println("indexOf:" + s.indexOf("owo"));//4
            System.out.println("----------------------");
    
            // int indexOf(int ch,int fromIndex): returns the index of the first occurrence of the specified character from the specified position in this string.
            System.out.println("indexOf:" + s.indexOf('l', 4));//8
            System.out.println("indexOf:" + s.indexOf('k', 4)); // -1
            System.out.println("indexOf:" + s.indexOf('l', 40)); // -1
            System.out.println("----------------------");
    
            // int indexOf(String str,intfromIndex): returns the index of the specified string where it first appears from the specified position in the string.
            System.out.println("indexOf:" + s.indexOf("owo", 4));//4
            System.out.println("indexOf:" + s.indexOf("ll", 4)); //-1
            System.out.println("indexOf:" + s.indexOf("ld", 40)); // -1
            System.out.println("----------------------");
    
            // String substring(int start): intercepts the string from the specified position, and defaults to the end. Contains the index start
            System.out.println("substring:" + s.substring(5));//world
            System.out.println("substring:" + s.substring(0));//helloworld
            System.out.println("----------------------");
    
            // String substring(int start,int
            // end): intercept the string from the specified position to the end of the specified position. Include the start index but not the end index
            System.out.println("substring:" + s.substring(3, 8));//lowor
            System.out.println("substring:" + s.substring(0, s.length()));//helloworld
    
            /**
             * Gets each character in the string
             */
            for(int i=0;i<s.length();i++){
                System.out.println(s.charAt(i));
            }
        }
    }
    

    4, Conversion function

    byte[] getBytes() //Convert string to byte array. 
    
    char[] toCharArray() //Converts a string to an array of characters.
    
    static String valueOf(char[] chs) //Convert a character array into a string.
    
    static String valueOf(int i) //Convert the data type of String to int. Note: the valueOf method of String class can convert any type of data into a String.
    
    String toLowerCase() //Convert the string to lowercase.
    
    String toUpperCase() //Convert string to uppercase.
    
    String concat(String str) //Concatenate strings.
    

    5, Other functions

    //Replacement function:
    String replace(char old,char new)
    
    String replace(String old,String new)
    
    //Remove spaces at both ends of the string
    String trim()
    
    //Compares two strings in dictionary order
    int compareTo(String str)
    int compareToIgnoreCase(String str)
    

    Source code analysis of compareTo() method:

    private final char value[]; //Automatically converts to an array of characters.
    /**
    * give an example
      String s6 = "hello";
      String s9 = "xyz";
      System.out.println(s6.compareTo(s9));// -16
    */
    public int compareTo(String anotherString) {
        int len1 = value.length;
        int len2 = anotherString.value.length;
    
        int lim = Math.min(len1, len2); //lim=3
        char v1[] = value; //v1[h e l l o]
        char v2[] = anotherString.value;//v2[x y z]
    
        int k = 0;
        while (k < lim) {
            char c1 = v1[k];//h
            char c2 = v2[k];//x
            if (c1 != c2) { //The first comparison is whether the corresponding characters are equal
                return c1 - c2; //h=104  x=120   104-120=-16
            }
            k++;
        }
        //If the characters are the same at the specified position, the length is subtracted
        return len1 - len2;
    }
    

    6, Practice

    Exercise 1: splice the data in the array into a string according to the specified format. Example: int[] arr = {1, 2, 3}; Output result: [1, 2, 3]

    /**
     *
     * Requirement: splice the data in the array into a string according to the specified format
     * give an example:
     *         int[] arr = {1,2,3};
     * Output result:
     *        "[1, 2, 3]"
     * analysis:
     *         A:Define a string object, but the content is empty
     *         B:First splice the string into a "["
     *         C:Traverse the int array to get each element
     *         D:First judge whether the element is the last one
     *             Yes: just splice the elements and "]"
     *             No: just splice elements and commas and spaces
     *         E:Output spliced string
     */
    public class StringTest2 {
        public static void main(String[] args) {
            int[] arr={1,2,3,4};
            System.out.println(arrayToString(arr));
        }
    
        /**
         * Concatenate the data in the array into a string according to the specified format
         */
        public static String arrayToString(int[] arr){
            String str="[";
            for(int i=0;i<arr.length;i++){
                if(i==arr.length-1){
                    str+=arr[i];
                }else{
                    str+=arr[i]+",";
                }
            }
            str+="]";
            return str;
        }
    }
    

    Exercise 2: count the number of occurrences of large and small strings

    /**
     * Count the number of occurrences of large and small strings
     * give an example:
     *         In the string "woaijavawozhenaijavawozheneaijavawozhendehnaijavaxinbuxinwoaijavagun"
     * result:
     *         java Five times
     *
     * analysis:
     *         Premise: you already know the big string and the small string.
     *         A:Define a statistical variable with an initialization value of 0
     *         B:First, find the position where the small string appears for the first time in the large string (boolean contains(String str): judge whether the large string contains a small string)
     *             a:If the index is - 1, it indicates that it does not exist, then the statistical variable is returned
     *             b:The index is not - 1, indicating that there is a statistical variable++
     *         C:Take the length of the index + small string as the starting position, intercept the last large string, return a new string, and re assign the value of the string to the large string
     *         D:Back to B
     */
    public class StringTest3 {
        public static void main(String[] args) {
            String s1="woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun";
            String s2="java";
            System.out.println(smallCount(s2,s1));
        }
    
        // Count the number of occurrences of large and small strings
        public static int smallCount(String smallStr,String bigStr) {
            int count=0;
    
            int index=bigStr.indexOf(smallStr);
            while(index!=-1){
                count++;
                //Take the index + the length of the small string as the starting position to intercept the last large string
                int startIndex=index+smallStr.length();
                bigStr=bigStr.substring(startIndex);
                index=bigStr.indexOf(smallStr);
            }
            return count;
        }
    }
    

    String buffer

    Common member methods

    //Construction method of StirngBuffer
    public StringBuffer() //Nonparametric construction method
    
    public StringBuffer(int capacity) //String buffer object with specified capacity
    
    public StringBuffer(String str) //Specifies the string buffer object for the string content
    
    //StringBuffer method
    public int capacity() //Returns the current capacity. Theoretical value
    
    public int length() //Returns the length in characters. actual value
    

    Use example:

    public static void main(String[] args) {
        // public StringBuffer(): parameterless construction method
        StringBuffer sb = new StringBuffer();
        System.out.println("sb:" + sb);
        System.out.println("sb.capacity():" + sb.capacity()); //The default specified capacity of StringBuffer is 16
        System.out.println("sb.length():" + sb.length());//0
        System.out.println("--------------------------");
    
        // public StringBuffer(int capacity): string buffer object with specified capacity
        StringBuffer sb2 = new StringBuffer(50);
        System.out.println("sb2:" + sb2);//""
        System.out.println("sb2.capacity():" + sb2.capacity());//50
        System.out.println("sb2.length():" + sb2.length());//0
        System.out.println("--------------------------");
    
        // public StringBuffer(String str): Specifies the string buffer object of the string content
        StringBuffer sb3 = new StringBuffer("hello");
        System.out.println("sb3:" + sb3);//hello
        System.out.println("sb3.capacity():" + sb3.capacity());//16+5=21
        System.out.println("sb3.length():" + sb3.length());//5
    }
    

    Add function

    public StringBuffer append(String str) 
    //You can add any type of data to the string buffer and return the string buffer itself
    
    public StringBuffer insert(int offset,String str) 
    //Insert any type of data into the string buffer at the specified position and return the string buffer itself
    

    Use example:

    public static void main(String[] args) {
        // Create string buffer object
        StringBuffer sb = new StringBuffer();
    
        // Chain programming
        sb.append("hello").append(true).append(12).append(34.56);
        System.out.println("sb:" + sb);
    
        // public StringBuffer insert(int offset,String
        // str): insert any type of data into the string buffer at the specified position, and return the string buffer itself
        sb.insert(5, "world");
        System.out.println("sb:" + sb);
    }
    

    Delete function

    public StringBuffer deleteCharAt(int index) 
    //Deletes the character at the specified position and returns itself
    
    public StringBuffer delete(int start,int end) 
    //Delete the content starting from the specified location and ending at the specified location, and return to itself
    

    Use example:

    public static void main(String[] args) {
        // create object
        StringBuffer sb = new StringBuffer();
    
        // Add function
        sb.append("hello").append("world").append("java");
    
        // public StringBuffer deleteCharAt(int index): deletes the character at the specified position and returns itself
        // Requirement: I want to delete the character e, what should I do?
        //sb.deleteCharAt(1);
        //public StringBuffer delete(int start,int end): deletes the content that starts at the specified location and ends at the specified location, and returns itself
        // Requirement: I want to delete the string world. What should I do?
        //sb.delete(5, 10);
        //Requirement: delete all characters
        sb.delete(0,sb.length());
        System.out.println("sb:" + sb);
    }
    

    Replacement function

    public StringBuffer replace(int start,int end,String str) 
    //Replace with str from start to end
    

    Use example:

    public static void main(String[] args) {
        // Create string buffer object
        StringBuffer sb = new StringBuffer();
    
        // Add data
        sb.append("hello");
        sb.append("world");
        sb.append("java");
        System.out.println("sb:" + sb);
    
        // public StringBuffer replace(int start,int end,String str): replace with str from start to end
        // Demand: I want to replace the data of world with "happy holidays"
        sb.replace(5,10,"Happy holidays");
        System.out.println("sb: "+sb);
    }
    

    Reverse function

    public StringBuffer reverse()
    

    Use example:

    public static void main(String[] args) {
        // Create string buffer object
        StringBuffer sb = new StringBuffer();
    
        // Add data
        sb.append("Xia Qinglin loves me");
        System.out.println("sb:" + sb);//Xia Qinglin loves me
    
        // public StringBuffer reverse()
        sb.reverse();
        System.out.println("sb:" + sb);//I love Lin Qingxia
    }
    

    Interception function

    public String substring(int start) // Note that the interception returns a String instead of a StringBuffer
    
    public String substring(int start,int end)
    

    Use example:

    public static void main(String[] args) {
        // Create string buffer object
        StringBuffer sb = new StringBuffer();
    
        // Add element
        sb.append("hello").append("world").append("java");
        System.out.println("sb:" + sb);//sb:helloworldjava
    
        // Interception function
        // public String substring(int start)
        String s = sb.substring(5);
        System.out.println("s:" + s);//s:worldjava
        System.out.println("sb:" + sb);//sb:helloworldjava
    
        // public String substring(int start,int end)
        String ss = sb.substring(5, 10);//Left closed right open
        System.out.println("ss:" + ss);//ss:world
        System.out.println("sb:" + sb);//sb:helloworldjava
    }
    

    Conversion between String and StringBuffer

    public class StringBufferDemo7 {
        public static void main(String[] args) {
            String s="hello";
            System.out.println(stringToStringBuffer(s)); //hello
            System.out.println(stringBufferToString(stringToStringBuffer(s)));//hello
        }
    
        // String -->StringBuffer
        public static StringBuffer stringToStringBuffer(String s) {
            // Note: the value of the string cannot be directly assigned to StringBuffer
            // StringBuffer sb = "hello";
            // StringBuffer sb = s;
    
            // Method 1: through the construction method
          /*  StringBuffer sb = new StringBuffer(s);
            return sb;*/
            // Method 2: through the append() method
            StringBuffer sb2 = new StringBuffer();
            sb2.append(s);
            return sb2;
        }
    
        //StringBuffer -->String
        public static String stringBufferToString(StringBuffer buffer){
            // Method 1: through the construction method
           /* String str = new String(buffer);
            return str;*/
            // Method 2: through toString() method
            String str2 = buffer.toString();
            return str2;
        }
    }
    

    practice

    Exercise 1: splice an array into a string

    public class StringBufferTest {
        public static void main(String[] args) {
            int[] arr={1,2,3,4};
            System.out.println(arrToString(arr));//[1,2,3,4]
        }
    
        public static String arrToString(int[] arr){
            StringBuffer buffer=new StringBuffer();
            buffer.append("[");
            for(int i=0;i<arr.length;i++){
                if(i==arr.length-1){
                    buffer.append(arr[i]);
                }else{
                    buffer.append(arr[i]).append(",");
                }
            }
            buffer.append("]");
            return buffer.toString();
        }
    }
    

    Exercise 2: determine whether a string is symmetrical

    /**
     *  Determine whether a string is a symmetric string
     * For example, "abc" is not a symmetric string, "aba", "abba", "aaa", "mnanm" is a symmetric string
     *
     * analysis:
     *         To judge whether a string is symmetrical or not, I just need to
     *             First and last comparison
     *             Second and penultimate comparison
     *             ...
     *         The number of comparisons is length divided by 2.
     */
    public class StringBufferTest2 {
        public static void main(String[] args) {
            System.out.println(isSymmetry("aba")); //true
            System.out.println(isSymmetry2("aabbaa"));//true
        }
    
        //Compare by character array
        public static boolean isSymmetry(String s){
            boolean flag=true;
            char[] chs=s.toCharArray();
            int len=chs.length;
            for(int start=0,end=chs.length-1;start<=end;start++,end--){
                if(chs[start]!=chs[end]){
                    flag=false;
                    break;
                }
            }
            return flag;
        }
    
         //reverse through StringBuffer
        public static boolean isSymmetry2(String s){
            //Obtain the inverted string s2 through the reverse of StringBuffer
            String s2=new StringBuffer(s).reverse().toString();
            return s2.equals(s);
        }
    }
    

    Exercise 3: look at the program and write the results

    public class StringBufferTest3 {
        public static void main(String[] args) {
            String s1 = "hello";
            String s2 = "world";
            System.out.println(s1 + "---" + s2);
            change(s1, s2);
            System.out.println(s1 + "---" + s2);
    
            StringBuffer sb1 = new StringBuffer("hello");
            StringBuffer sb2 = new StringBuffer("world");
            System.out.println(sb1 + "---" + sb2);
            change(sb1, sb2);
            System.out.println(sb1 + "---" + sb2);
        }
    
        //StringBuffer is passed as a parameter
        public static void change(StringBuffer sb1, StringBuffer sb2) {
            sb1 = sb2;
            sb2.append(sb1);
        }
    
        //String is passed as a parameter
        public static void change(String s1, String s2) {
            s1 = s2;
            s2 = s1 + s2;
        }
    }
    

    Output result:

    hello---world
    hello---world
    hello---world
    hello---worldworld
    

    String is passed as a parameter, and the effect is the same as that of basic type.

    Stringļ¼Œ StringBuffer and StringBuilder

    1. Variability

  • String immutable
  • StringBuffer and StringBuilder variable
  • String is immutable, so it is thread safe
  • StringBuilder is not thread safe
  • StringBuffer is thread safe and uses synchronized internally for synchronization
  • The operation of String objects in Java is actually a process of constantly creating new objects and recycling old objects, so the execution speed is very slow
  • StringBuffer will operate on the StringBuffer object itself every time, instead of generating a new object and changing the object reference
  • StringBuilder will operate on the StringBuilder object itself every time, instead of generating a new object and changing the object reference. In the same case, using StirngBuilder can only improve the performance by about 10% ~ 15% compared with using StringBuffer, but it takes the risk of unsafe multithreading.
  • Operate a small amount of data, using String
  • Single thread operation operates a large amount of data under the string buffer, using StringBuilder
  • Multithreading operates a large amount of data in the string buffer, using StringBuffer

Keywords: Java Back-end

Added by shane0714 on Sat, 19 Feb 2022 01:17:59 +0200