当前位置:网站首页>String analysis and use

String analysis and use

2022-06-10 21:55:00 Hua Weiyun

  I finished my study today JAVA The first chapter of this lesson is the analysis and use of string classes , Finish this chapter , I have mastered the following two points , Namely String class 、StringBuffer and StringBuil class .

One .String Class analysis

  String Class is often used before, but we haven't explained the specific knowledge points of this class and how to use this class , Then we will learn this class systematically . First pair String Class to do some analysis , Summarize the main knowledge points .

  1. String Class char Array holds data
  2. String It's a final class , uninheritable
  3. String Is an immutable class , After the object is generated , The content cannot be changed
  4. String Class String Member methods of type objects will return a new String Type object

Two .String Class comparison

  String Class overridden equals() Method , Used to compare two strings Is the content the same . Similar to this is "==", This is also to compare whether it is the same , Just and equals() Compare things differently ,"==" Compare two String The address of the type object Are they the same? .

  The case code is as follows :

public class StringDemo {	public static void main(String[] args) {		// TODO Auto-generated method stub		String s1 = new String("123");		String s2 = new String("123");		System.out.println(s1==s2);				String s3 = "234";		String s4 = "456";		System.out.println(s3==s4);				System.out.println(s1.equals(s2));	}}

3、 ... and . String class instantiation mechanism

  Like other classes you create yourself ,String Classes also create object instances , Then let's learn Java How to create String Object's .

  Java establish String There are two ways to object

  1.   At the time of creation ,JVM You will now find whether the object exists in the string constant pool , If there is , Directly return the address of the string object , without , Just create the object in the constant pool and return the address

            // The first way

            String s1 = "123";

     2.  At the time of creation , It will also first look for the string in the constant pool , If there is , Just copy the object in the heap , And pass the address of the object in the heap to the variable ; If it doesn't exist , The string objects will be created in the heap and in the constant pool respectively , And return the address of the object in the heap , You create two objects and store them in two places

           // The second way

          String s2 = new String("123");

          // Create objects only in the constant pool , Created an object

          String s1 = "123";

          // Create one object in the constant pool and one object in the heap , There are two in all

          String s2 ="123”;

Four . String maintenance and parameter passing

  String Class "+" and concat() Two strings can be spliced together , Form a new string . But the two are different , The difference is "+" String and non string can be spliced together , and concat() Only strings and strings can be concatenated . The case code is as follows :

public class StringDemo2 {	public static void main(String[] args) {		String s1 = "123";		System.out.println(s1+123);		System.out.println(s1.concat("123"));	}}

  String Parameter transfer of : First look at the code

	public static void main(String[] args) {		String s1 = new String("123");		show(s1);		System.out.println(s1);	}	public static void show(String s) {		s = "234";	}}

  Look at the output of this code 123 still 234 Well ? yes 123, Next, let's talk about why 123, Let's talk about the process of transferring parameters .

  1. We are main Function to create a new object 123, And then sent its address to s1, So now s1 What's stored is 123 Address in the pile
  2. call show() Method , And the s1 Pass in , Shape parameter s Copied arguments s1 Value , That is to say s1 Stored address , Now? s It also points to 123 The address in the heap .
  3. Get into show Method post execution s="234", Is to put 234 This object is assigned to s,s The address stored in is 234 The address of . But this operation is for arguments s1 No impact ,s1 It's still stored in 234 The address of .
  4. show() After the end , Shape parameter s disappear , object 234 Because there is no reference to it , So it will be recycled by the garbage collection mechanism .
  5. Print s1 still 123

5、 ... and . Common use of strings API Method

  String Common methods of class :

  1. equals(): Used to compare whether the contents of two strings are the same
  2. charAt(): Returns the character at the specified index
  3. contains(): Determine whether the string contains another string
  4. indexOf(): Returns the index of the first occurrence of a string
  5. isEmpty(): Determine whether the string is empty
  6. split(): Splits the string in the specified format , Return string array
  7. trim(): Remove spaces at the beginning and end of a string
  8. toCharArray(): Convert string to character array
  9. replace(): Replace a character or string in a string , All replacement
  10. length(): Returns the length of the string

  The case code is as follows :

import java.util.Arrays;public class StringDemo4 {	public static void main(String[] args) {		String s = "hello world";				System.out.println(s.charAt(1));//e				System.out.println(s.contains("e"));				System.out.println(s.indexOf("e"));// If you can't find it , return -1				System.out.println(s.isEmpty());//false				String[] ss = s.split(" ");// Split the string with a space as a flag 		System.out.println(Arrays.toString(ss));				System.out.println(s.trim());				char[] sss = s.toCharArray();		System.out.println(Arrays.toString(sss));				System.out.println(s.replace("l", "e"));				System.out.println(s.lastIndexOf("l"));//9   Returns the last occurrence of the index 	}}

6、 ... and .StringBuffer class

  StringBuffer Also called variable character sequence , Thread safe variable character sequence . It is a similar to String String buffer for , Can't modify , But you can change the contents and length of the sequence by calling some methods . You can put StringBuffer Think of it as a container , This container contains many strings , And you can manipulate these strings .StringBuffer It is synchronous and safe , This follow-up will talk about , When sharing resources with multiple threads, it is necessary to ensure synchronization safety

public class StringDemo4 {	public static void main(String[] args) {		// Create an empty object StringBuffer		StringBuffer sb = new StringBuffer();		System.out.println(sb);		System.out.println(sb.capacity());// The size of the output container   The buffer defaults to 16		System.out.println(sb.length());// The length of the output object 				// Create a string buffer of the specified size 		StringBuffer sb2 = new StringBuffer(50);		System.out.println(sb2);		System.out.println(sb2.capacity());		System.out.println(sb2.length());				// Create a string buffer for the specified string contents 		StringBuffer sb3 = new StringBuffer("hello");		System.out.println(sb3);		System.out.println(sb3.capacity());// The default is 16, Now? hello The length is 5, The capacity is added to 21 了 		System.out.println(sb3.length());	}		//StringBuffer It's a sequence of variable strings , Capacity and length can be changed }

7、 ... and .StringBuilder class

  StringBuil and StringBuffer similar , Are all string buffers , Asynchronous security

package com.huawei.string;/* * StringBuilder  It is also a string buffer , Out of sync . If you want to compare two StringBuilder Are the instances the same , To convert to String class  */public class StringDemo5 {	public static void main(String[] args) {		String str = new String("abc");		StringBuilder stringBuilder = new StringBuilder(str);				System.out.println(" Generate a string buffer using a parameterized constructor "+stringBuilder);// Got it abc, Because it is stored in the string buffer abc				// Use the empty construction method to create StringBuilder object 		StringBuilder builder = new StringBuilder();		System.out.println(" Null parameter constructed string buffer "+builder);		//StringBuilder No rewriting equals()  If you have to compare StringBuilder Is the content the same , Then you have to StringBuilder convert to String		String s1 = builder.toString();				StringBuilder builder2 = new StringBuilder();		System.out.println(" Null parameter constructed string buffer "+builder2);		String s2 = builder2.toString();				// First, compare the two directly StringBuilder Example 		System.out.println(builder.equals(builder2));//false, There is no content in these two instances , It should be the same , But the output is false, So to compare , It must be converted into String				System.out.println(s1.equals(s2));//true					}}

  Now let's summarize String,StringBuffer,StringBuilder The difference between :

  • String The content is variable
  • StringBuffer and StringBuilder The content of is variable
  • StringBuffer It's synchronous , Data is secure but inefficient
  • StringBuilder It's not synchronous , Data is insecure but efficient

  You can know from the following code results ,sb Is always less than 1000, and sb1 The value of is always 1000, therefore StringBuild It's out of sync

public class Test {	StringBuilder sb = new StringBuilder();	StringBuffer sb1 = new StringBuffer();		public Test() {		// Create thread groups to manage threads 		ThreadGroup group = new ThreadGroup("testGroup");		// Create thread class objects 		MyThread at = new MyThread();		// Turn on 100 Threads 		for(int i=0;i<1000;i++) {			Thread th = new Thread(group,at,String.valueOf(i));			th.start();		}				while(group.activeCount()>0) {// This method returns the number of thread groups in the current thread of the active thread 			try {				Thread.sleep(10);			} catch (InterruptedException e) {				// TODO Auto-generated catch block				e.printStackTrace();			}					}				System.out.println(sb.length());		System.out.println(sb1.length());	}	class MyThread implements Runnable{		@Override		public void run() {			// TODO Auto-generated method stub			try {				Thread.sleep(10);			} catch (InterruptedException e) {				// TODO Auto-generated catch block				e.printStackTrace();			}						sb.append("1");			sb1.append("1");		}			}		public static void main(String[] args) {		new Test();		//StringBuilder To reach 1000, Out of sync ,StringBuffer Has always been a 1000, It's synchronous 	}}

8、 ... and . summary

  After learning these contents, I have mastered String Class

原网站

版权声明
本文为[Hua Weiyun]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206101708316891.html