[Java foundation] 2020.01.07 object class

Common methods of Object class

Method name Function description
public boolean equals(Object obj) Compare two objects for equality
public final Class getClass() Gets the type of the current object and returns the Class object
public String toString() Converts the current object to a string
protected Object clone() Generates a backup of the current object and returns the copy
public int hashCode() Returns the hash code of the current object

1.equals() method

equals method in Object class

    public boolean equals(Object obj) {
        return (this == obj);
    }

equals method in Integer class

    public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }

equals method in String class

   public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

① = = compares the addresses of two objects. In the Object parent class, equals is equivalent==
② Basic data type is compared with = =
③ The equals method in the Object class compares the addresses of the two objects, but it has been rewritten in many classes to compare the contents of the two objects, such as String class and Integer class
Example 1:

	public static void main(String[] args) {
		Integer obj1 = new Integer(5);
		Integer obj2 = new Integer(15);
		Integer obj3= new Integer(5);
		Integer obj4 = obj2;
		System.out.println("obj1 And obj2 Comparison:"+obj1.equals(obj2));//false
		System.out.println("obj1 And obj3 Comparison:"+obj1.equals(obj3));
				//The true integer class overrides the equal class to compare whether the contents of the two objects are equal
		System.out.println("obj2 And obj4 Comparison:"+obj2.equals(obj4));//true
		System.out.println("**************************");
		System.out.println("obj1 And obj2 Comparison:"+(obj1==obj2));//false address is different
		System.out.println("obj1 And obj3 Comparison:"+(obj1==obj3));//false address is different
		System.out.println("obj2 And obj4 Comparison:"+(obj2==obj4));//true, two references are the same address
	}

Example 2:

public static void main(String[] args) {
		Integer obj1 = new Integer(5);
		Integer obj2 = new Integer(15);
		Integer obj3= new Integer(5);
		Integer obj4 = obj2;
		System.out.println("obj1 And obj2 Comparison:"+obj1.equals(obj2));//false
		System.out.println("obj1 And obj3 Comparison:"+obj1.equals(obj3));
				//The true integer class overrides the equal class to compare whether the contents of the two objects are equal
		System.out.println("obj2 And obj4 Comparison:"+obj2.equals(obj4));//true
		System.out.println("**************************");
		System.out.println("obj1 And obj2 Comparison:"+(obj1==obj2));//false address is different
		System.out.println("obj1 And obj3 Comparison:"+(obj1==obj3));//false address is different
		System.out.println("obj2 And obj4 Comparison:"+(obj2==obj4));//true, two references are the same address
		
	}

2.toString() method

The toString() method in the Object class is used to obtain the description information of the Object. The method returns a string containing the class name and hash code.
Use the following format
getClass().getName()+'@'+Integer.toHexString(hashCode())

3.String() class

1. String type overview

The String class represents a String, and all String literals (such as "abc") in a java program are implemented as instances of this class. In other words, all double quotation marks in Java programs are objects of the String class. The String class is under the java.lang package, so you don't need to import the package when you use it!

2. Characteristics of String class

1. Strings are immutable, and their values cannot be changed after creation
2. Although String values are immutable, they can be shared
3. String effect is equivalent to character array (char []), but the underlying principle is byte array (byte [])

3. The difference between two ways of creating string objects

① Created by construction method
For the string object created through new, each time new requests one memory space. Although the contents are the same, the address values are different
② Direct assignment creation
As long as the character sequence is the same (sequence and case), the JVM will only create a String object and maintain it in the String pool no matter how many times it appears in the program code.
Example:

		//Three initialization methods of string
		String str1 = "I am string!";
		String str2 = new String("I am string!");
		String str3 ;

4. Different types and string type conversion

		str3 = "I am string";
		//String - > integer
		int number = 1;
		String str4 = number + "";
		int number1 = 1;
		String str5 = Integer.toString(number1);
		//Integer - > string
		String str6 ="123";
		int number3 = Integer.parseInt(str6);
		//Floating point - > string
		double number4 = 3.14;
		String str7 = number4 + "";
		String str8 = Double.toString(number4);
		//String - > floating point
		String str9 = "1.23";
		double number5 = Double.parseDouble(str9);

5. string common methods

Method Explain
charAt(int index) Returns the character corresponding to the specified subscript index
concat(String str) Connecting two strings returns the combined string
endsWith(String suffix) true/false to determine whether a character ends in a suffix string
startWith(String suffix) true/false to determine whether a character begins with a suffix string
equals(Object obj) Judge whether two strings are equal, true/false
indexOf(String suffix) Return the subscript corresponding to the substring suffix
lastIndexOf(String suffx) Returns the last occurrence of the substring suffix in the string
length() Returns the length of the string
matches(String regex) Determine whether a string matches a regular expression
replace(char oldChar, char newChar) Replace old substring oldChar with new substring newChar in string
split(String regex) Split the string by regex and return the string array
substring(int beginIndex, int endIndex) Intercepts the substring within the index range and returns the substring [beginindex, endindex)
trim() Space before and after string removal

Demo:

package com.hyg.StringDemo;

public class StringReverseDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(reverse("qwertgyhju"));
	}
	public static String reverse(String string){
		String result = "";
		for(int i = string.length()-1;i>=0;i--){
			result = result+string.charAt(i);
		}
		return result;
	}

}


Demo2:

package com.hyg.StringDemo;

public class StringIndexOfDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String string ="helloworld!";
		int i = string.indexOf("l");
		int a = string.indexOf("he");
		int b = string.indexOf("worlde");
		System.out.println("i="+i+" ,a = "+a+",b  = "+b);
		String string1 = string.substring(2);
		String string2= string.substring(2,5);
		System.out.println("string1="+string1+" ,string2= "+string2);
		String str = "  heool world!  ";
		System.out.println(str.trim());
		System.out.println();
	}

}

Demo3:

package com.hyg.StringDemo;

import java.util.Scanner;

public class CharAtDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		String string = sc.nextLine();
		sc.close();
		char c;
		int big = 0,small = 0,num = 0;
		for (int i = 0; i < string.length(); i++) {
			c = string.charAt(i);
			if (48 <= c && c <= 57) //number
				num++;
			if (65 <= c && c <= 90) //Capitalization
				big++;
			if (97 <= c && c <= 122) //A lowercase letter
				small++;
		}
		System.out.println("Capitalized"+big+"In figures"+small+"Number has"+num+"individual"+string);
	}

}

6. The difference between String, StringBuffer and StringBuilder

String: any change to its content will result in new objects, which are suitable for strings with small number of operations.
StringBuffer: any change to its content will not generate new objects. It is suitable for strings with a large number of operations. It is fast and suitable for multi-threaded operations. Common methods include append() append and reverse() content inversion.
StringBuilder: any change to its content will not produce new objects. It is suitable for strings with large number of operations, with fast operation speed, unsafe threads and unsuitable for multi-threaded operations.

* Note

1. Inner class: access modifiers can also be added
2. Sibling: access modifiers cannot be added. A Java file can have multiple siblings, but only one public class
3. Integer class is a wrapper class for int

38 original articles published, praised 13, visited 6307
Private letter follow

Tags: Java jvm

Posted on Wed, 15 Jan 2020 02:33:16 -0500 by tobimichigan