Java foundation consolidation (Object class (toString(), equals(), hashCode() methods), String string class, StringBuffer, StringBuilder class)

1. Object class

Java is an object-oriented language. The core idea is to find the right object to do the right thing:

    
    Method 1: Customize the class, and then create an object through the customized class.
    
    Method 2: sun provides a lot of classes for me to use, we only need to know these classes, we can create objects through these classes.
    
The Object class is the ultimate parent class of all classes. Any class inherits the Object class.


Object class:


Common methods of Object class:
    toString(); Returns the string representation of the object. Returns a string describing the object.
Question: What does toString() do? After rewriting toString, when we output an object directly, it will output the format data that meets our needs.
    
    equals(Object obj) is used to compare the memory addresses of two objects to determine whether the two objects are the same object.
    
    hashCode() returns the hash code value of the object (you can understand the hash code as the memory address of the object)/


Specifications in java: Generally, if we override the equals method of a class, we will override its hashCode method.

class Person{
	
	int id;
	
	String name;

	public Person(int id, String name) {
		this.id = id;
		this.name = name;
	}

	public Person() {
	}
	
	//At present, when I need to output an object directly, the output format is: No.: 110 Name: dog baby in this format. The current Object
// The toString method cannot meet the needs of subclasses, so we should rewrite the toString of the Object class at this time.
	@Override
	public String toString() {
		return "Number: "+ this.id + " Name: "+this.name;
	}
	
	
	//Why rewrite: Object's equals method compares the memory addresses of two objects by default. What I need to compare is the IDs of the two objects, so the equals method of the Object class does not meet my current needs.
	@Override
	public boolean equals(Object obj) {
		Person p  = (Person)obj;
		return this.id== p.id;
	}
	
	@Override
	public int hashCode() {
		return  this.id;
	}
	
		
}


public class Demo1 {

	public static void main(String[] args) {
		
		/*
		Object o = new Object();
		System.out.println(o.toString()); // The string representation returned by java.lang.Object@18b3364: full class name+@+ hash code of the object
		System.out.println(o); // By looking at the source code, we know that when an object is directly output, the toString method of this call will actually be called inside the println method, and the content returned by the toString method will be output.
		//Question: Why is the string result returned by the toString method of the output object the same when outputting an object directly?
		
		
		Person p1 = new Person(110,"Doll");
		System.out.println("p1:"+p1);  
		//If we can output a p object, the format of the output: ID: 110 Name: dog baby..
		Person  p2 = new Person(112,"狗剩");
		System.out.println("p2:"+p2);  
		*/
		
		
		Person p1 = new Person(110,"Doll");
		Person p2 = new Person(110,"陈富贵");
		//Requirements: In real life, as long as two people's ID cards are the same, they are the same person.
		System.out.println("Is p1 and p2 the same object?"+ p1.equals(p2));
		
		System.out.println("p1 hash code: "+ p1.hashCode());
		System.out.println("p2 hash code: "+ p2.hashCode());
		
		
	}
	
	
	
}
Second, the String string class

(1) String characteristics: Strings are constants; their values ​​cannot be changed after creation.

 
 Once the content of the string changes, a new object will be created immediately.
 
 Note: The content of the string is not suitable for frequent modification, because once modified, a new object will be created immediately.
 
 If you need to modify the content of the string frequently, it is recommended to use the string buffer class (StringBuffer).
 
                String str1 = "hello";
		String str2 = "hello";
		String str3 = new String("hello");
		String str4 = new String("hello");
		System.out.println("str1==str2?"+(str1==str2));  // true  
		System.out.println("str2==str3?"+(str2==str3));  //false
		System.out.println("str3==str4?"+(str3==str4));  // false
		System.out.println("str3.equals(str2)?"+(str3.equals(str4))); //true
		//It is the String class that overrides the equals method of Object to compare whether the contents of the two string objects are consistent.
		// "==" is used to compare the memory addresses of the two objects when comparing the data of the reference data type. The equals method compares the memory addresses of the two objects by default.

(2) String constructor:
 
     String() creates a string object with empty content.
     String(byte[] bytes) Constructs a string object using a byte array
     String(byte[] bytes, int offset, int length)
         bytes : The array to decode
         offset: Specifies to start decoding from the index value in the array.
         length: Multiple elements to decode.
     
     String(char[] value) constructs a string using an array of characters.    
     String(char[] value, int offset, int count) Constructs a string using an array of characters, specifying the starting index value, and the number of characters to use.
    String(int[] codePoints,int offset,int count)
    String(String original)

Remember: A string object can be constructed using either a byte array or a character array.
public class Demo2 {
	
	public static void main(String[] args) {
		String str = new String();
		byte[] buf = {97,98,99};
		
		str = new String(buf); //build a string object using a byte array
		str = new String(buf,1,2); //Construct a string object using a byte array, specifying the index value to start decoding and the number of decoding.
		
		char[] arr = {'Ming','Day','Yes','Saint','Christmas'};
		str = new String(arr); //build a string from an array of characters
		str = new String(arr,3,2);
		
		int[] 	buf2 = {65,66,67};
		str = new String(buf2,0,3);
		
		str = new String("abc");
		
		
		System.out.println("Content of string: "+str);
		
		
		
		
	}
	
}

(3) Get method
    int length() Get the length of the string
    char charAt(int index) Get the character at a specific position (the corner mark is out of bounds)
    int indexOf(String str) Find the index value of the first occurrence of the substring, if the substring does not appear in the string, then it returns -1.

    int lastIndexOf(String str) Find the index value of the last occurrence of the substring, if the substring does not appear in the string, then return -1 to indicate

public class Demo3 {
	
	public static void main(String[] args) {
		String str = "abcChinaabChina";
		System.out.println("Number of characters in the string: " + str.length() );
		System.out.println("Get the corresponding character according to the index value: "+ str.charAt(3));
		System.out.println("Find the index value of the first occurrence of the substring: " + str.indexOf("China"));
		System.out.println("Find the index value of the last occurrence of substring: " + str.lastIndexOf("China"));
		
	}
	

}
(4) Judging whether the method
    boolean endsWith(String str) ends with the specified character
    boolean isEmpty() whether the length is 0 such as: "" null V1.6
    boolean contains(CharSequences) Whether it contains the specified sequence Application: search for
    boolean equals(Object anObject) Is it equal
    boolean equalsIgnoreCase(String anotherString) Ignore whether the case is equal

(5) Conversion method     
char[] toCharArray() Convert string to character array byte
[] getBytes();

can be converted to each other.
public class Demo4 {
	
	public static void main(String[] args) {
		String str = "Demo.java";
		System.out.println("Whether it ends with the specified string: "+ str.endsWith("ja"));
		//str = "";
		System.out.println("Determine whether the string is empty: "+str.isEmpty());
		System.out.println("Determine whether the string contains the specified content: "+ str.contains("Demo"));
		System.out.println("Determine whether the contents of the two strings are consistent: "+ "DEMO.JAVA".equals(str));
		System.out.println("Determine whether the contents of two strings are consistent (ignoring case comparison):"+ "DEMO.JAVA".equalsIgnoreCase(str));
		
		
		// method of conversion
		char[] buf = str.toCharArray(); //Convert string to character array
		System.out.println("Character array: "+ Arrays.toString(buf));
		byte[] buf2 = str.getBytes(); // Convert string to byte array
		System.out.println("Byte array: "+ Arrays.toString(buf2));
	}

}

(6) Other methods
    String replace(String oldChar, String newChar) Replace
    String[] split(String regex) Cut
    
    String substring(int beginIndex) Specify the starting index value to intercept the substring
    String substring(int beginIndex, int endIndex) specify the starting and The ending index value intercepts the substring
    
    String toUpperCase() Converts to uppercase
    String toLowerCase() Converts to lowercase
    String trim() Removes spaces at the beginning and end of the string
public class Demo5 {
	
	public static void main(String[] args) {
		String str = "No exam tonight";
		System.out.println("Specify the new content to replace the old content:"+ str.replace("No", "Be good"));
		str = "Everyone-afternoon-good";
		String[] arr = str.split("-"); //Split according to the specified character.
		System.out.println("Content of string array: "+ Arrays.toString(arr));
		str = "Guangzhou Chuanzhi Podcast";
		System.out.println("The specified starting index value intercepts the substring: "+ str.substring(2));
		System.out.println("The specified starting index value intercepts the substring: "+ str.substring(2,6)); //The header does not include the end Note: The intercepted content includes the index value of the beginning, not the end The index value, the intercepted position is the ending index value -1.
		
		str = "abCChina";
		System.out.println("Upper case: " + str.toUpperCase());
		str = "AbdfSDD";
		System.out.println("转小写:"+ str.toLowerCase());
		
		str = "Everyone has been working very hard lately";
		System.out.println("Remove spaces at the beginning and end of the string: "+ str.trim());
		
		
	}

Three, StringBuffer, StringBuilder class

If you need to modify the content of the string frequently, it is recommended to use the string buffer class (StringBuffer).



StringBuffer is actually a container for storing characters.

Written test question: What is the default initial capacity when an object is created using the no-argument constructor of Stringbuffer? If the length is not enough, how many times will it automatically increase?
    The bottom layer of StringBuffer relies on a character array to store character data. The default initial capacity of the string array is 16. If the length of the character array is not enough, it will automatically double.


StringBuffer is a container for storing characters. The behavior of the

container is
    
    String
    
    addition
        append(boolean b) You can add any type of data to the container
        insert(int offset, boolean b) Specify the inserted index value and insert the corresponding content.

    Delete
        delete(int start, int end) Delete the corresponding content according to the specified start and end index values.
        deleteCharAt(int index) deletes a character according to the specified index value.
    
    
    Modify
    
        replace(int start, int end, String str) to replace the specified content with the specified start and end index values.
        reverse() reverses the contents of the string buffer class. abc--->cba
        
        setCharAt(int index, char ch) Replaces the specified character with the character at the specified index.
        substring(int start, int end) Truncates the substring according to the specified index value.
        ensureCapacity(int minimumCapacity) Specifies the length of the character array inside the StringBuffer.
        
    Look at
        indexOf(String str, int fromIndex) Finds the index value of the first occurrence of the specified string, and specifies the position to start the search.
        lastIndexOf(String str)
        
        capacity() View the length of the current character array.
        length()
        
        charAt(int index)
        toString() Convert the content of the string buffer class into a string and return it.
        

Similarities and differences between StringBuffer and StringBuilder:
    
    Similarities:
        1. Both classes are string buffer classes.
        2. The methods of both classes are the same.
    Differences:
        1. StringBuffer is thread-safe and has low operation efficiency, while StringBuilder is thread-unsafe and has high operation efficiency.
        2. StringBuffer appeared in jdk1.0, and StringBuilder appeared in jdk1.5.
        
Recommended use: StringBuilder, because the operation is efficient.
        
public class Demo2 {
	
	public static void main(String[] args) {
		//First create a string buffer class using the StringBuffer no-argument constructor.
		StringBuffer sb = new StringBuffer();
		sb.append("abcjavaabc");
		/*
		Add to
		sb.append(true);
		sb.append(3.14f);
		insert
		
		sb.insert(2, "小明");
		*/
		
		/*
		delete
		sb.delete(2, 4); // When deleting, it is also the header but not the end
		sb.deleteCharAt(3); //Delete a character according to the specified index value
		
		Revise	
		sb.replace(2, 4, "Puppy Chen");
		
		sb.reverse(); // reverse the contents of the string
		
		sb.setCharAt(3, 'red');
		
		String subString = sb.substring(2, 4);
		System.out.println("Substring content: "+ subString);
		
		Check
	
		int index = sb.indexOf("abc", 3);
		System.out.println("Index value: "+index);
			
		sb.append("javajava");
		System.out.println("Check the length of the character array: "+ sb.capacity());
		*/
		
		System.out.println("Number of characters stored: "+sb.length());
		System.out.println("Search character at the specified index value: "+sb.charAt(2) );
		System.out.println("Content of string buffer class: "+ sb);
		
		String content = sb.toString();
		test(content);
	}
	
	public static void test(String str){
		
	}
	
}



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324857401&siteId=291194637
Recommended