Inner class
Local inner class
/*
About the local inner class, its writing position, the class defined in the member method of the outer class
Local internal classes can access member variables of external classes, including private variables!
In the local location of the external class, access the member methods of the internal class and create the current local internal class object to access!
*/
class Outer{ public int num = 100 ; private int num2 = 200 ; //Member method public void method(){ //Local location: local inner class class Inner{ //A member method of a local inner class public void show(){ System.out.println(num); System.out.println(num2); } } //Create a local internal class object Inner inner = new Inner() ; inner.show() ; } } //Test class public class OuterDemo { public static void main(String[] args) { //Access method: directly create external class objects //Called member method Outer outer = new Outer() ; outer.method(); } }
Local internal classes access local variables
/*
When a local internal class accesses a local variable, what should the local variable pay attention to? (JDK7/JDK8), why add the final keyword?
reason:
1. The life cycle of a local variable exists with the method call and disappears with the end of the method call. When the current external class object calls the method method method, num enters the stack memory and creates a local internal class object at the local location
2. The local internal class object calls its member methods to access the variable. After the method method method ends, the internal class object will not disappear immediately. When its member methods access the local variable, the local variable must become a constant and reside in memory. Otherwise, if the current variable disappears, the members of the local internal class will still access the variable, and there will be a conflict! Therefore, jdk7 must add the final modification after receiving it. jdk8 has been optimized through the jvm, so there is no need to add the final modification manually
*/
class Outer2{ public void method(){ int num = 20 ; //local variable class Inner2{ public void show(){ System.out.println(num); } } //Create Inner2 class object Inner2 inner2 = new Inner2() ; inner2.show(); } } //Test class public class OuterDemo2 { public static void main(String[] args) { //Create Outer2 object Outer2 outer2 = new Outer2() ; outer2.method(); } }
Anonymous Inner Class
/*
Inner class without name
Generally used in our local location!
Format:
Anonymous inner class, which is a simplified form of inner class
new class name (either abstract or concrete) or interface name (){
Rewrite function
} ;
The nature of anonymous inner classes:
It inherits this class or is a subclass object that implements this interface
*/
//Define an interface interface Inter{ void show() ; //public abstract modification (can be omitted) 2 void show2() ; } /*class InterImpl implements Inter{ @Override public void show() { } @Override public void show2() { } }*/ //External class class Outer3{ //Define a member method public void method(){ // class Inner3{} has an inner class with a name //Use anonymous inner classes to write /* new Class name (either abstract or concrete) or interface name (){ Rewrite function } ; */ //Case 1: there is only one method in the interface /* new Inter(){ //Interface name @Override public void show() { System.out.println("show Inter..."); } }.show() ;*/ //Case 2: there are two methods in the interface /* new Inter(){ @Override public void show() { System.out.println("show Inter..."); } @Override public void show2() { System.out.println("show2 Inter..."); } }.show() ; new Inter(){ @Override public void show() { System.out.println("show Inter..."); } @Override public void show2() { System.out.println("show2 Inter..."); } }.show2() ;*/ //Optimization: give an anonymous inner class a name Inter i = new Inter(){ @Override public void show() { System.out.println("show Inter..."); } @Override public void show2() { System.out.println("show2 Inter..."); } }; i.show(); i.show2(); } } //Test class public class OuterDemo3 { public static void main(String[] args) { //Create Outer3 class object Outer3 outer3 = new Outer3() ; outer3.method(); } }
Use of anonymous inner classes in development
The formal parameter of a method is an abstract class
If the formal parameter of a method is an abstract class, the actual parameter can require a subclass object of the interface
1) Subclasses are defined and inherited from abstract classes
2) Anonymous inner classes that use abstract classes directly
//abstract class abstract class Person{ public abstract void work() ; } //PersonDemo class class PersonDemo{ public void method(Person p){//The formal parameter of a method is an abstract class p.work(); } } //Define a subclass that inherits from the Person class class Student extends Person{ @Override public void work() { System.out.println("good good study ,day day up!!"); } } //Test class public class PersonTest { public static void main(String[] args) { //Call the method method in the PersonDemo class? //Create a PersonDemo class object and / or an anonymous object PersonDemo pd = new PersonDemo() ; //Abstract class polymorphism: creating subclass objects Person p = new Student() ; //Define a subclass Student pd.method(p) ; System.out.println("----------------------------------------"); //Use anonymous inner classes to complete: /** * new Class name (abstract class) / interface name (){ * override method * } ; */ //Call the method method in the PersonDemo class? PersonDemo pd2 = new PersonDemo() ; pd2.method(new Person(){ //The actual parameter is also a subclass object that passes the abstract class (the anonymous inner class of the abstract class) @Override public void work() { System.out.println("good good Study,day day Up!!"); } }); } }
The formal parameter of the method is an interface
If the formal parameter of the method is an interface, the interface subclass object actually needs to be passed
Method 1: define the sub implementation classes of the interface
Mode 2; Anonymous inner class using interface
//Define an interface interface Mary{ void mary() ; } //Define a LoveDemo class class LoveDemo{ public void funciton(Mary mary){//The formal parameter is an interface mary.mary(); } } //Define a subclass implementation class class You implements Mary{ @Override public void mary() { System.out.println("I'm getting married,Very happy..."); } } //Test class public class LoveTest { public static void main(String[] args) { //Method 1: you need to call the function method in the LoveDemo class LoveDemo loveDemo = new LoveDemo() ; //Or use anonymous objects //Interface polymorphism Mary mary = new You() ; loveDemo.funciton(mary); System.out.println("----------------------------------------"); //Method 2: anonymous inner class of interface //Create a LoveDemo class object LoveDemo ld = new LoveDemo() ; ld.funciton(new Mary() { @Override public void mary() { System.out.println("I'm getting married,Very happy..."); } }); } }
The return value of the method is an abstract class
What needs to be returned is the subclass object of the current abstract class
abstract class Person{ public abstract void work() ; } class PersonDemo{ public Person method(){ //return ? //Abstract class polymorphism // Person person = new Programmer() ; // return person ; // return new Programmer() ; //Anonymous inner class of direct abstract class return new Person(){//Equivalent to a subclass object of the Person class (the essence of an anonymous inner class) @Override public void work() { System.out.println("Programmers knock code day and night"); } } ; } } //Define a subclass class Programmer extends Person{ @Override public void work() { System.out.println("Programmers knock code day and night..."); } } //Test class public class PersonTest { public static void main(String[] args) { //Call the method method in the PersonDemo class PersonDemo pd = new PersonDemo() ; Person person = pd.method(); //Person pserson = new Programmer() ; person.work(); System.out.println("--------------------------"); //Method 2: anonymous inner class PersonDemo pd2 = new PersonDemo() ; Person p = pd2.method(); p.work(); } }
The return value of the method is an interface
Returns a subclass object of the current interface
interface Love{ void love() ; } class LoveDemo{ public Love function(){ //return ? //Polymorphism through interface //Love love = new Student() ; //return love ; //Anonymous object // return new Student() ; //Anonymous inner class using interface /** * new Class name / interface name (){ * * override method * } ; */ return new Love(){ @Override public void love() { System.out.println("love Java,like to study..."); } } ; } } //Define sub implementation classes of the interface class Student implements Love{ @Override public void love() { System.out.println("love Java,like to study..."); } } //Test class public class LoveTest { public static void main(String[] args) { //To access the function method in the LoveDemo class LoveDemo ld = new LoveDemo() ; Love love = ld.function();//Love love = new Student() ; love.love(); System.out.println("------------------"); //Method 2: interface anonymous inner class LoveDemo ld2 = new LoveDemo() ; Love l = ld2.function(); l.love(); } }
Internal interview question 1
Test site:
- External classes directly access the format of non static member internal classes
- The method mode of the member variable of the external class, (in the member method of the internal class of the member)
- The names of member variables and local variables are the same (proximity principle)
- There is no inheritance relationship between external class and internal class
class Outer{ int num = 10 ; //Member inner class class Inner{ int num = 20 ; public void show(){ int num = 30; //Completion code System.out.println(num); System.out.println(this.num);//This limit: this Variable name: the member variable of the current class // System.out.println(new Outer().num) ; // Method 1: new outer() num System.out.println(Outer.this.num) ; //Method 2: this restriction of external class } } } public class OuterTest { public static void main(String[] args) { Outer.Inner oi = new Outer().new Inner() ; oi.show(); } }
Internal interview question 2
Written test questions
Complete the code - > output "HelloWorld" on the console
Given an interface
- interface Inter{
-
void show() ;
- }
- class Outer{
-
//Completion code
- }
- class Test{
-
public static void main(String[] args){
-
Outer.method().show() ;
-
}
- }
interface Inter{ void show() ; } class Outer2{ public static Inter method(){ //Return results? //The return value is an interface type. What needs to be returned is the sub implementation class object of the interface //Method 1: define subclasses (let's not create subclasses) //Method 2: you can use the interface anonymous inner class (test site) return new Inter(){ @Override public void show() { System.out.println("HelloWorld..."); } } ; } } public class Test { public static void main(String[] args) { /* Inter inter = Outer2.method(); //Inter inter = new Subclass implementation (); Anonymous inner class inter.show() ;*/ Outer2.method().show(); /** * Class name Method() ---- > indicates that the current method is a static method * Outer2.method().show()---->Front part outer2 Method() --- > is a method of return value type. You can call the show method in the interface * show Method is an interface method, so the returned interface type * */ } }
Object: the root class of the class hierarchy: Java lang.Object
Object interview questions
How many ways can I get the bytecode file object of a class? Three kinds
-
The first method: through getClass() of Object class - > class: running java class: class package name Class name
-
The second: the class attribute of any Java type -- get the bytecode file object class of the current class
-
The third type: forName("fully qualified name of class (package name. Class name)") in class; (most used)
public class ObjectDemo { public static void main(String[] args) throws ClassNotFoundException { //Create a student class object Student s = new Student() ; Class c1 = s.getClass(); System.out.println(c1);//class com. qf. generator_ class_ 05. Student class package Class name Class c2 = s.getClass(); System.out.println(c2);//class com. qf. generator_ class_ 05. Student class package name Class name System.out.println(c1 == c2); //==In the basic data type, the data values are the same. In the reference type, the address values of the two objects are the same //Student. Class - > Load once System.out.println("---------------------------------"); Student s2 = new Student() ; System.out.println(s == s2);//false: two objects System.out.println("----------------------------------"); //Gets the fully qualified name of the class represented by c1/c2 // Class ---->class com.qf.generator_class_05.Student String name1 = c1.getName(); String name2 = c2.getName(); System.out.println(name1); System.out.println(name2); System.out.println("--------------------------------"); //public static Class forName(String classname) in Class: used in post reflection Class c3 = Class.forName("com.qf.generator_class_05.Student"); System.out.println(c1==c3); System.out.println(c2==c3); System.out.println("--------------------------------"); Class c4 = Student.class ; //Class attribute of any Java type -- get the bytecode file object class of the current class System.out.println(c4); System.out.println(c1==c4); System.out.println(c2==c4); System.out.println(c3==c4); System.out.println("---------------------------------------"); //Create two objects // public int hashCode() Student s3 = new Student() ; Student s4 = new Student() ; System.out.println(s3.hashCode()); System.out.println(s4.hashCode()); System.out.println("helloworld".hashCode()); System.out.println("javaee".hashCode()); System.out.println("helloWorld".hashCode()); System.out.println("helloworld".hashCode()); } }
public String toString() of Object
Returns the string representation of the object. The result should be a concise expression that is easy to read.
Description of an object: it is composed of many attributes (member variables). You should see the specific attribute description
- Manual mode (not recommended)
- You can also directly press the shortcut key to override toString
public class Student extends Object { String name ; int age ; public Student() { } public Student(String name, int age) { this.name = name; this.age = age; } //Manually override toString of Object /* @Override public String toString() { return "The name is "+ name +" and the age is "+ age"; }*/ //Alt + ins - > tostring() @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}';//Member information expression describing student object } } public class ObjectDemo { public static void main(String[] args) { //Create a student object through the parametric construction method Student s = new Student("Gao Yuanyuan",42) ; //Direct output Object name -- > will call its parent class: toString method of Object by default System.out.println(s);//com.qf.object_06.Student@1540e19d System.out.println("-----------------------------------"); /** * Object The original code of the toString method of the class * public String toString() { * return getClass().getName() + "@" + Integer.toHexString(hashCode()); * } * * Integer Class: wrapper type of int type * public static String toHexString(int i) :Convert integers to hexadecimal data -- the results are displayed in String type */ /*System.out.println(s.getClass().getName()+"@"+Integer.toHexString(s.hashCode())); System.out.println(s.toString());*/ System.out.println(s.toString()); /*String str = new String("hello") ; System.out.println(str);*/ } }
equals method of Object class
What is the difference between equals and =?
- ==: basic data type of connection: compare whether the data values are the same
- ==: the connected is a reference type, and the comparison is whether the address values are the same
public class Student { String name ; int age ; public Student() { } public Student(String name, int age) { this.name = name; this.age = age; } //Override toString of Object class @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } //Override the equals and code methods //First, compare whether the hash code values of s1 and s2 are the same @Override public int hashCode() { int result = name.hashCode();//name:String "article" hashCode() ; eight hundred and thirty-seven thousand one hundred and seventy-seven result = 31 * result + age; //31 * 837177 + 35 return result; //Get a result } //After comparing the hash code values, it is also necessary to determine whether the member contents are the same (name - "Chinese characters") //s1.equals(s2) @Override public boolean equals(Object o) { //Object o = new Student() ; Student s2 = new Student() ; if (this == o) return true; //if(this==o) {/ / if the address values of the current s1 object and s2 object are the same //return true ; // } if (o == null || getClass() != o.getClass()) return false; //If the s2 object is null or the current S1 Getclass() and s2 Getclass() bytecode file objects are different, and false is returned directly Student student = (Student) o; //Downward Transformation: O --- > student student if (age != student.age) return false; //Judge whether the age is the same (S1) this age != student. age (s2) return name.equals(student.name); //The name is a String //s1.name.equals(s2.name) ; //The equals method of the Object class has been overridden at the bottom of the String type itself, so the direct comparison is whether the contents of the String are the same } } public class ObjectDemo { public static void main(String[] args) { //== int a = 10 ; int b = 15 ; System.out.println(a==b);//==Linked basic data type: compare whether the data values are the same System.out.println("--------------------------------------------"); Student s1 = new Student("article",35) ; System.out.println(s1); Student s2 = new Student("article",35) ; System.out.println(s2); System.out.println(s1 == s2); System.out.println("--------------------------------------"); //public boolean equals(Object obj)//Object obj = new Student() ; polymorphic System.out.println(s1.equals(s2)); //Before rewriting: the Object class equals() is executed //After rewriting, you will compare whether the member information of the object is consistent! System.out.println(s1.hashCode()); System.out.println(s2.hashCode()); System.out.println("article".hashCode()); /*** *Object Class * public boolean equals(Object obj) { //s1 ---this obj---->s2 * return (this == obj); return s1 == s2 ; ==:Reference type: compares whether the address values are the same * } */ System.out.println("---------------------------------------------"); // String type (most common classes override equals) overrides the equals method of Object, so whether the comparison content is the same String str1 = "hello" ; String str2 = "hello" ; System.out.println(str1.equals(str2)); String str3 = "world" ; String str4 = new String("world") ; System.out.println(str3.equals(str4)); } }
Cloning method
To use the clone method, the class of the current Object must implement the "tag interface" Cloneable (no fields (member variables) or member methods). Then you can use the clone() method of the Object
public class Student implements Cloneable{ private String name ; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Student() { } public Student(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } } public class ObjectDemo { public static void main(String[] args) throws CloneNotSupportedException{ //Create student object Student s1 = new Student("Gao Yuanyuan",42) ; System.out.println(s1); System.out.println(s1.getName()+"---"+s1.getAge()); System.out.println("-----------------------------------"); //Call the clone method clone() Object obj = s1.clone(); //Already cloned (shallow cloning: assign s1 address value to Objet) //Downward transformation Student s2 = (Student) obj; System.out.println(s2); System.out.println(s2.getName()+"---"+s2.getAge()); System.out.println("-----------------------------------"); //Traditional way Student s3 = s1 ; System.out.println(s3.getName()+"---"+s3.getAge()) } }
Scanner: text scanner: Java util. Scanner
Scanner interview questions
The Scanner class provides the judgment function: prevent the mismatch between the input type and the result type!
Solution;
- 1) Directly use next() --- > string
- 2) Before using nextLine(), just create a Scanner object
Unified first use string ----- > receive all ----- > later, the Integer ----- > string can be used through the unique function of Integer
Precondition: String - > numeric string "1", "2", "3"
public class ScannerDemo { public static void main(String[] args) { //Create keyboard entry object InputStream inputStream = System.in ; //Standard input stream IO(Input read, Output write): Java advanced features: IO Scanner sc = new Scanner(inputStream) ;// public Scanner(InputStream source): create a text scanner System.out.println("Please enter a data:"); if(sc.hasNextInt()){ int num = sc.nextInt() ; System.out.println("The data you entered is:"+num); }else if(sc.hasNextLine()){ //Entered string String line = sc.nextLine() ; System.out.println("The data you entered is:"+line); }else{ System.out.println("The data you entered does not match the result type..."); } //Input data // int num = sc.nextInt(); //java.util.InputMismatchException // System.out.println("the data you want to enter is:" + num); } }
String: String: Java lang.String
Get function of String class
Get function name | Functional meaning |
---|---|
int length() | Get string length |
public char charAt(int index) | Gets the character at the specified index |
public String concat(String str) | Splice the specified string with the current string to obtain a new string |
public int indexOf(int ch) | Returns the index value of the first occurrence of the specified character |
public String[] split(String regex) | Split function: splits a string into an array of strings in a specified format |
public String substring(int beginIndex) | : from the specified position, the default interception is to the end, and the corner mark starts from 0 |
public String substring(int beginIndex,int endIndex) | From the specified location to the end of the interception location (not the right before the package), only endIndex-1 can be obtained |
public class StringDemo { public static void main(String[] args) { String str = "helloworldJavaEE" ; // public char charAt(int index); Gets the character at the specified index System.out.println("charAt():"+str.charAt(4)); System.out.println("---------------------------------"); //public String concat(String str): splice the specified string with the current string to obtain a new string //The most traditional splicing of strings: directly define a string s = ""; S + any data = "xxx"; //Provides a function System.out.println("concat:"+str.concat("R").concat("Go")); System.out.println("-----------------------------------"); // public int indexOf(int ch): returns the index value of the first occurrence of the specified character // public int lastIndexOf(int ch): return the index value of the last occurrence of the specified character System.out.println("indexOf():"+str.indexOf("o")); System.out.println("lastIndexOf():"+str.lastIndexOf("o")); System.out.println("-----------------------------------"); //public String[] split(String regex): String str2 = "JavaEE-Python-Go-R-C-C#-PHP" ; //Split with "-" String[] strArray = str2.split("-"); for(int x = 0 ; x < strArray.length ; x ++){ System.out.print(strArray[x]+"\t"); } System.out.println(); System.out.println("-----------------------------------"); /** * public String substring(int beginIndex) :From the specified position to the end by default * Corner markers start at 0 * public String substring(int beginIndex,int endIndex) */ // String str = "helloworldJavaEE" ; System.out.println("subString():"+str.substring(5)); System.out.println("subString():"+str.substring(5,9));//worl System.out.println("-----------------------------------"); //Public static string valueof (basic type and Object) System.out.println("valueOf:"+String.valueOf(100)); //100--->"100" } }
Judgment function of String class
Judgment function method | Functional meaning |
---|---|
public boolean equals(Object anObject) | Compare whether the contents of two characters are the same (case sensitive) |
public boolean equalsIgnoreCase(String anotherString) | Compares whether two strings are the same (case insensitive) |
public boolean startsWith(String prefix) | Determines whether the string starts with the specified content |
public boolean endsWith(String suffix) | Determines whether the string ends with the specified content |
boolean isEmpty() | Judge whether the string is empty: if it is empty, return true; Otherwise, false is returned |
public class StringDemo2 { public static void main(String[] args) { String s1 = "helloJavaEE" ; String s2 = "hellojavaee" ; // public boolean equals(Object anObject): compares whether the contents of two characters are the same (case sensitive) System.out.println("equals:"+s1.equals(s2)); // public boolean equalsIgnoreCase(String anotherString) System.out.println("equalsIgnoreCase():"+s1.equalsIgnoreCase(s2)); /** * public boolean startsWith(String prefix):Determines whether the string starts with the specified content * public boolean endsWith(String suffix):Determines whether the string ends with the specified content * boolean isEmpty() Judge whether the string is empty: if it is empty, return true; Otherwise, false is returned */ System.out.println("startsWith():"+s1.startsWith("hel")); System.out.println("startsWith():"+s1.startsWith("ak47")); System.out.println("endsWith():"+s1.endsWith("EE")); s1 = "" ; //Length() --- > length 0 (empty character sequence) System.out.println(s1.isEmpty()); } }
Conversion function of String class
Conversion function method | Method meaning |
---|---|
byte[] getBytes() | Convert string to byte array (encoding) |
byte[] getBytes(String charset) | Encodes using the specified character set |
public static String toString(int/byte/float/double...[] a) | Array of any type ----- > string |
public char[] toCharArray() | Convert string to character array |
public String toString() | Return itself - "content of current string" |
public String toUpperCase() | Convert string to uppercase |
public String toLowerCase() | Convert string to lowercase |
public class StringDemo { public static void main(String[] args) throws UnsupportedEncodingException { //Define a string String str = "China" ; byte[] bytes = str.getBytes();//Default utf-8 // byte[] bytes = str.getBytes("gbk");// Specify character set // public static String toString(byte[] a) System.out.println(Arrays.toString(bytes));//[-28, -72, -83, -27, -101, -67] //[-42, -48, -71, -6] System.out.println("------------------------------"); //decode // String strResult = new String(bytes,"gbk") ;//gbk: one Chinese corresponds to two bytes. / / decode using the platform default decoding set: utf-8 String strResult = new String(bytes) ;// //Decoding using the platform default decoding set: utf-8 System.out.println(strResult); System.out.println("--------------------------------------"); //Define a string String s2 = "helloworldJavaEE" ; // public char[] toCharArray() char[] chs = s2.toCharArray(); //Traversal character array for(int x = 0 ; x < chs.length; x ++){ System.out.println(chs[x]); } System.out.println("-----------------------"); System.out.println(s2.toString()); System.out.println("-----------------------"); //Convert case System.out.println(s2.toUpperCase()); System.out.println(s2.toLowerCase()); } }
Other functions of String class
Function name | Functional meaning |
---|---|
public String replace(char target,char replacement) | Replace with the specified character target |
public String replaceAll(String regex, String replacement) | Replace the specified string that matches the regular expression of parameter 1 with replacement |
public String trim() | Remove spaces at both ends of the string |
public int compareTo(String anotherString) | Compared in dictionary order, the return value is int |
public class StringDemo2 { public static void main(String[] args) { String s = "helloworld" ; System.out.println("replace():"+s.replace('l','k')); System.out.println("-------------------------------------"); //public String trim(): remove spaces at both ends of the string // /** * In web pages; When filling in the date * Application scenario: * In the IO stream: "hello" during data transmission, you can remove spaces through trim (for data transmission in the network, after obtaining string data, remove spaces first, and then operate!) * String Text "2021-7-27" ----- > Date object date * Parsing process: if there are spaces in the date text, an exception will occur in the string ---- > parsing. Remove the spaces at both ends */ String s2 = "hello"; System.out.println("s2:"+s2+"----"); String s3 = " hello " ; System.out.println("s3:"+s3); System.out.println("s3:"+s3.trim()+"----"); System.out.println("------------------------------------"); // Public int CompareTo (string otherstring): compare in dictionary order. The return value is int String str1 = "abc" ;//Dictionary order: our 26 letters, a,b,c,d,e,f,g,h String str2 = "hello" ; System.out.println(str1.compareTo(str2)); String str3 = "hel" ; System.out.println(str2.compareTo(str3)); } }
Construction method of String class
method | Method meaning |
---|---|
public String() | Null parameter Construction: null character sequence |
public String(byte[] bytes) | Construct a byte array into a string, using the platform's default character set |
public String(byte[] bytes, character set) | Constructs a byte array into a string using the specified character set |
public String(byte[] bytes,int offset,int length) | Converts the length of the parameter 1: to the specified byte of the parameter array, and converts the specified byte of the parameter 1: to the specified byte of the parameter array |
public String(char[] value) | Construct a character array into a string |
public String(char[] value,int offset,int count) | Converts a partial character array to a string |
public String(String original) | Construct a string with the parameter string constant |
public class StringDemo { public static void main(String[] args) { //test String s = new String() ; System.out.println("s:"+s); //String class overrides toString() of Object, System.out.println(s.length()); System.out.println("-------------------------------------------"); byte[] bytes = {97,98,99,100,101} ; // public String(byte[] bytes) String s2 = new String(bytes) ; System.out.println(s2); System.out.println(s2.length()); System.out.println("-------------------------------------------"); //public String(byte[] bytes,int offset,int length): String s3 = new String(bytes,2,2) ; System.out.println(s3); System.out.println(s3.length()); System.out.println("-------------------------------------------"); //public String(char[] value) char[] chs = {'I','love','high','circular','circular'} ; String s4 = new String(chs) ; System.out.println(s4); System.out.println(s4.length()); System.out.println("-------------------------------------------"); // public String(char[] value,int offset,int count) String s5 = new String(chs,1,4) ; System.out.println(s5); System.out.println(s5.length()); System.out.println("---------------------------------------------"); // public String(String original) String s6 = new String("hello") ; //Create a string object, constant value: hello System.out.println(s6); String s7 = "hello" ; //Recommended way System.out.println(s7); } }
equals method of String class
==And equals
- ==: connection reference types compare address values
- Equals: compare address values by default, but the String class overrides the equals method, so are the contents the same
public class StringTest { public static void main(String[] args) { String s1 = "hello" ; String s2 = "world" ; String s3 = "helloworld" ; System.out.println(s3 == (s1+s2)); //s1+s2: open space first, false in splicing System.out.println(s3.equals(s1+s2)); //true System.out.println("----------------------"); System.out.println(s3 == "hello"+"world"); //Splice first, and then find it in the constant pool. If it exists, it will directly return the address System.out.println(s3 .equals("hello"+"world")); } }
Traversal of String class
Output each character of the string separately!
You can use the acquisition function of String class: charat (int index) -- > char
//Loop improvement: use length() of String class to obtain String length + charAt(int index) for(int x = 0 ;x < str.length() ; x ++){ System.out.println(str.charAt(x));//charAt(0) } System.out.println("--------------------------------"); //Use the conversion function of the String class //String --- > character array tochararray() --- > char [] char[] chs = str.toCharArray(); for(int x = 0 ; x < chs.length ; x ++){ char ch = chs[x] ; System.out.println(ch); }
Figure guessing game
Requirements:
- Know a user name and password, then enter the user name and password with the keyboard, and give three chances,
- If the user name and password remain unchanged, you will be prompted with "login succeeded", ------> start the number guessing game (definition class: static function in StartGame: start())
- If the opportunity runs out, change the prompt "account is locked, please contact the administrator"
- If not, prompt "you have xxx opportunities left"
public class StringTest { public static void main(String[] args) { // 1) Given user name and password String username = "admin" ; String password = "admin" ; //2) Cycle 3 opportunities for(int x = 0 ; x < 3 ;x ++){ //Create keyboard entry object Scanner sc = new Scanner(System.in) ; //Prompt and enter data System.out.println("Please enter your user name:"); String name = sc.nextLine() ; System.out.println("Please enter your password:"); String pwd =sc.nextLine() ; if(username.equals(name) && password.equals(pwd)){ System.out.println("Login succeeded,Ready to play the game..."); StartGame.start(); break ; //end } //When the opportunity runs out if((2-x)==0){ System.out.println("I'm sorry,Your account is locked,Please contact the administrator"); }else{ System.out.println("What's left of you"+(2-x)+"Second chance"); } } } } public class StartGame { //Static function public static void start(){ //Generate a random number int num = (int) (Math.random()*100+1); while(true){ //Keyboard input data Scanner sc = new Scanner(System.in) ; //Prompt and enter data System.out.println("Please enter a data(1-100):"); int guessNumber = sc.nextInt() ; //compare if(guessNumber > num){ System.out.println("The data you have to guess is too big..."); }else if(guessNumber < num){ System.out.println("The data you have to guess is small..."); }else{ System.out.println("Congratulations,You guessed right"); break ; } } } }
String inversion (String)
-
A known array is statically initialized, and the array is spliced into a String (improved with function)
-
Define a function to convert an array into a String, and the return value is String [element 1, element 2, element 2...]
-
Splicing:
+: splice symbols
concat(): splicing function
public class StringTest2 { public static void main(String[] args) { //Create array, static initialization int[] arr = {11,22,33,44,55} ; String str = array2String(arr); System.out.println(str); //+---- > using the Stringconcat function } /** * Defines a function that converts an array to a String type * Two clear * 1)Specify the return value type: String * 2)Specify the parameter type and the number of parameters * A parameter, an array of type int */ public static String array2String(int[] arr){ //Define an empty string String result = "" ; //Splice left bracket result +="[" ; //Traverse the arr array to get each element for(int x = 0 ; x < arr.length ; x ++){ //Determine whether it is the largest angle mark if(x == arr.length-1){ result += arr[x] ; result +="]" ; }else{ //Splice commas and spaces result += arr[x] ; result += ", "; } } return result ; } }
Symmetric string
Enter a string on the keyboard: judge whether the string is symmetrical:
public class StringTest4 { public static void main(String[] args) { //Create keyboard entry object Scanner sc = new Scanner(System.in) ; //Prompt and enter data System.out.println("Please enter a string:"); String line = sc.nextLine() ; //Call function boolean flag = compare(line) ; System.out.println(flag); //Functions of comparison private static boolean compare(String line) { //Create a new character array and initialize dynamically char[] charArray = new char[line.length()] ; //Traverse the line string and get each character through charAt(int index) for(int x = 0 ; x < line.length() ; x ++){ charArray[x] = line.charAt(x) ;//Assign a character to each element in the character array } //Traverse the character array charArray to ensure the length of / 2 for(int i = 0 ; i < charArray.length/2 ; i ++){ //Judge I = 0 chararray [0] chararray [array. Length-1-0] //i= 1 charArray[1] charArray[arr.length-1-1] if(charArray[i] !=charArray[charArray.length-1-i]) { return false; } } return true ; } }
String interview question 1
Is there a length method in the array, a length method in the String class, and a length method in the collection
- There is no length method in the array, length attribute
int[] arr = new int[3] ;
arr.length; - length() in String class
- There is no length () in the collection, and ------ > size () gets the number of elements
String interview question 2
String s1 = "hello" ;
String s2 = new String("hello") ;
How many objects are created in memory?
- The first one creates an object directly in the constant pool to open up the constant pool space
- Second: two objects are created, one to open up space in heap memory and one to point to constant pool (not recommended)
public class StringDemo2 { public static void main(String[] args) { String s1 = "hello" ; String s2 = new String("hello") ; System.out.println(s1 == s2); System.out.println(s1.equals(s2)); //Just the same } }
String interview question 3
Requirements:
- Enter a string on the keyboard: (excluding other special symbols)
- For example:
"hELLOWORLD", ------> truncate the first character to uppercase
All subsequent characters become lowercase
Result "Helloworld"
public class StringTest { public static void main(String[] args) { //Create keyboard entry object Scanner sc = new Scanner(System.in) ; //Prompt and enter data System.out.println("Please enter a string(Upper and lower case letters):"); String line = sc.nextLine() ; //1) Intercept the first substring in the string (0,1) String s1 = line.substring(0,1); //Convert the result -- > of s1 to uppercase String s2 = s1.toUpperCase() ; //Start with the second character in the string: truncate to the end by default String s3 = line.substring(1) ; //Convert the result of s3 to lowercase String s4 = s3.toLowerCase() ; //Splice s2 and s4 through concat String result = s2.concat(s4) ; System.out.println(result); System.out.println("----------------------------------"); //Chain programming String result2 = line.substring(0,1).toUpperCase().concat(line.substring(1).toLowerCase()) ; System.out.println(result2); } }
StringBuffer: string buffer
StringBuffer: thread safe class (low execution efficiency): string buffer: the character sequence stored in it
Get function of StringBuffer class
Get function name | Functional meaning |
---|---|
public int length() | Get the number of characters (length) |
public int capacity() | Gets the string buffer capacity |
Adding function of StringBuffer class
Add feature name | Functional meaning |
---|---|
StringBuffer append (any type) | Append content to string buffer |
public StringBuffer insert(int offset,String str) | Insert: inserts the specified content at the specified location |
public class StringBufferDemo { public static void main(String[] args) { //Create a string buffer object StringBuffer sb = new StringBuffer() ; System.out.println("sb:"+sb); //StringBuffer append (any type) sb.append("hello").append("world").append(100).append('a').append(12.34).append(new Object()) ; System.out.println("sb:"+sb); System.out.println("----------------------------------"); //public StringBuffer insert(int offset,String str) sb.insert(5,"Gao Yuanyuan") ; System.out.println("sb:"+sb); } }
Deletion function of StringBuffer class
Delete function name | Functional meaning |
---|---|
public StringBuffer deleteCharAt(int index) | Deletes the character sequence of the buffer at the specified index and returns the string buffer itself |
public StringBuffer delete(int start,int end) | Delete the character sequence from the specified position to the end of the specified position (including the character at end-1), and return the string buffer itself |
public class StringBufferDemo2 { public static void main(String[] args) { //Create a StringBuffer object (default initial capacity 16) StringBuffer buffer = new StringBuffer() ; buffer.append("hello").append("world").append("Javaee") ; System.out.println(buffer); System.out.println("---------------------------"); //public StringBuffer deleteCharAt(int index) //Delete e this character // System.out.println("deletCharAt():"+buffer.deleteCharAt(1)); //Delete the first l character // System.out.println("deletCharAt():"+buffer.deleteCharAt(1)); //public StringBuffer delete(int start,int end): //Delete the substring world System.out.println("delete():"+buffer.delete(5,10));//5-9 } }
Intercepting function of StringBuffer class
Interception function name | Functional meaning |
---|---|
public String substring(int start) | Starting from the specified position, it is intercepted to the end by default, and the return value is a new string |
public String substring(int start,int end) | Intercepts from the specified position to the end of the specified end-1, and returns a new string |
public class StringBufferDemo5 { public static void main(String[] args) { StringBuffer sb = new StringBuffer() ; sb.append("hello").append("world").append("javaee").append("anroid") ; System.out.println("sb:"+sb); // System. out. println(sb.substring(5));// Substring (XX) - -- > intercepted new string //System.out.println("sb:"+sb); // System.out.println(sb.substring(5,10));//end-1 position
Replacement function of StringBuffer class
Replace function name | Functional meaning |
---|---|
public StringBuffer replace (int start,int end,String str) | replace |
//public StringBuffer replace(int start, start index) // int end, end index (end-1) // String str) replaced content System.out.println(sb.replace(5,10,"Gao Yuanyuan"));
Inversion function of StringBuffer class
Unique function name | Functional meaning |
---|---|
public StringBuffer reverse() | After inversion, the string buffer itself is returned |
Construction method of StringBuffer class
Constructor name | Method meaning |
---|---|
public StringBuffer() | Null parameter construction to create a string buffer of null character sequence |
public StringBuffer(int capacity) | Construct a string buffer object to specify the capacity size |
public StringBuffer(String str) | Specifies the character sequence, the length plus the initial capacity of 16 (total capacity) |
String inversion (StringBuffer)
/**
*Reverse reverse function
*s inverts the specified string
*Return result string
*/
public class StringBufferDemo4 { public static void main(String[] args) { Scanner sc = new Scanner(System.in) ; //Prompt and enter System.out.println("Please enter a string:"); String line = sc.nextLine() ; //You need to use the unique function reverse of StringBuffer //Line - > StringBuffer type StringBuffer sb = new StringBuffer(line) ; String result = sb.reverse().toString(); System.out.println(result); System.out.println("-----------------------------"); //Call function String result2 = reverse(line); System.out.println(result2); } public static String reverse(String s){ //Step by step //Method 1: s ---- > StringBuffer type ---- > parameter construction //StringBuffer buffer = new StringBuffer(s) ; //return buffer.reverse().toString() ; //Method 2:append() + null parameter construction method /*StringBuffer buffer = new StringBuffer() ; String result = buffer.append(s).reverse().toString(); return result ;*/ //Anonymous object return new StringBuffer().append(s).reverse().toString() ; } }
Symmetric string (StringBuffer)
Function improvement of using StringBuffer
//Method 2: function improvement using StringBuffer boolean flag2 = compare2(line) ; System.out.println(flag2); } private static boolean compare2(String line) { /* //Set line --- > StringBuffer StringBuffer sb = new StringBuffer(line) ; String str = sb.reverse().toString(); return str.equals(line) ;*/ return new StringBuffer(line).reverse().toString().equals(line) ; }
Conversion between StringBuffer and String
Under development:
- Type A itself. Since type B functions need to be used, type a ----- > type B
- Type A requires the use of type B functions. Type A - > type B. after using the functions, type A may be required again,
- Type B ----- > type A
public class StringBufferDemo3 { public static void main(String[] args) { //String---->StringBuffer String s = "hello" ; //Wrong writing // StringBuffer sb = s ;// The two types are inconsistent //Method 1:StringBuffer parameterized construction method StringBuffer sb = new StringBuffer(s) ; System.out.println(sb); System.out.println("---------------------------"); //Method 2: the parameterless construction method of StringBuffer is combined with append(String str) StringBuffer sb2 = new StringBuffer() ; sb2.append(s) ;//Additional function System.out.println(sb2); System.out.println("-------------------------------------------"); //StringBuffer---->String //Create string buffer object StringBuffer buffer = new StringBuffer("helloJavaee") ; //Construction method of type string: 1 //public String(StringBuffer buffer) String str = new String(buffer) ; System.out.println(str); System.out.println("-------------------------------------------"); //Method 2: public String toString() method of StringBuffer String str2 = buffer.toString(); System.out.println(str2); } }
StringBuffer interview question 1
What is the difference between StringBuffer and array?
- Array: can only store containers of the same data type
Arrays can store both basic types and reference types
The biggest feature of array: fixed length
Static initialization int[] arr = {element 1, element 2, element 3...}/ Dynamic initialization int[] arr = new int [length];
String[] strArray = {"xx","xx","xx"} ; - StringBuffer: supports variable character sequences
It can store any type of element
append(int/char/double/float/Obejct/String) isnert(int offert,int/char/double/float/Obejct/String) general situation: StringBuffer - > string in development
StringBuffer interview question 2
What is the difference between StringBuffer,StringBuilder and String?
- String: string is a constant. Once assigned, its value cannot be changed / as a formal parameter, it belongs to a special reference type, and the change of formal parameter will not affect the actual parameter
- StringBuffer: variable character sequence, thread safe class ---- synchronous ----- > low execution efficiency (thread perspective)
- StringBuilder: variable character sequence And StringBuffer have mutually compatible APIs, which are used in single threaded programs (only execution efficiency is considered, and safety is not considered),
StringBuilder will be used instead of StringBuffer
public class StringBufferTest { public static void main(String[] args) { //int[] arr = {11,22,33,44,55} ;//int[] arr = new int[]{11,22,33,44,55} //System.out.println(Arrays.toString(arr)); String s = "hello" ; System.out.println("s:"+s);//hello change(s) ; System.out.println("s:"+s);//hello System.out.println("-------------------------"); StringBuffer sb = new StringBuffer("android") ; System.out.println("sb:"+sb);//android change(sb) ; System.out.println("sb:"+sb);//androidjavaee } public static void change(StringBuffer sb){//StringBuffer as formal parameter sb.append("javaee") ;//Java EE is appended to the cache System.out.println("sb:"+sb);//javaee } public static void change(String s) {//String as formal parameter: consistent with the basic data type (string is a constant) s = s +"worldjavaee" ; System.out.println("s:"+s);//helloworldjavaee } }
Integer
Integer: the wrapper class type (reference type) of int type, which contains the original data value of int type
Static functions of Integer:
Static function name | Functional meaning |
---|---|
public static String toBinaryString(int i) | Convert integer ---- > to binary string |
public static String toOctalString(int i) | Convert integer ---- > to octal string |
public static String toHexString(int i) | Convert integer - > hexadecimal data |
public static final int MAX_VALUE | Maximum value of int |
public static final int MIN_VALUE | Minimum value of int |
public class IntegerDemo { public static void main(String[] args) { System.out.println(Integer.toBinaryString(100)); System.out.println(Integer.toOctalString(100)); System.out.println(Integer.toHexString(100)); System.out.println("----------------------"); System.out.println(Integer.MIN_VALUE);//-The 31st power of 2 System.out.println(Integer.MAX_VALUE);//The 31st power of 2 - 1 } }
Construction method of Integer
Constructor name | Method meaning |
---|---|
Integer(int value) | int type can be guaranteed to be Integer type |
Integer(String s) throws NumberForamtException | Throw a number formatting exception |
public class IntegerDemo2 { public static void main(String[] args) { //Create an Integer class object int i = 100 ; Integer integer = new Integer(i) ; System.out.println(integer); System.out.println("---------------------"); //Create a string // String s = "hello" ; String s = "50" ; Integer integer2 = new Integer(s) ; System.out.println(integer2); } }
Automatic disassembly box of Integer
- Automatic disassembly box, variable parameters, static import, enhanced for loop, < generic >, enumeration class
- Basic type - > corresponding packing type (packing)
int---->Integer - Corresponding packing type ----- > basic type (unpacking)
public class IntegerDemo3 { public static void main(String[] args) { //Create an Integer class object int i = 100 ; Integer ii = new Integer(i) ; ii += 200 ; System.out.println("ii:"+ii); /** *View through decompile tool int i = 100; Integer ii = new Integer(i); //Create an Integer class object ii = Integer.valueOf(ii.intValue() + 200); ii = Integer.valueIf(Unpack first (integer - > int + 200) //Assign 300 to Integer variable ii, and the bottom layer uses valueof (int) - > int) - > Integer boxing System.out.println((new StringBuilder()).append("ii:").append(ii).toString());//Output as string */ } }
Integer interview questions
- Use int - > string integer as a bridge
- String---->int
public class IntegerDemo4 { public static void main(String[] args) { //int---->String int i = 50 ; //String result = "" ; //result = result + i ;// Splice symbol //System.out.println(result);//"50" //Use function //Method 1: static function of integer class //public static String toString(int i) String str = Integer.toString(i); System.out.println(str); System.out.println("------------------------"); //Method 2: int - > integer - > public string tostring() Integer ii = new Integer(i) ; String str2 = ii.toString(); //The underlying method public static String toString(int i) System.out.println(str2); System.out.println("----------------------------------"); //String --- > int (mostly used) //Under development: Browser (client) - -- > data passed to the back end (String type) //Method 1:public static int parseInt(String s)throws NumberFormatException: numeric string (most used) //General method: String - > long long parseLong(String s)---->long // String ----double Double public static double parseDouble(String s) String s = "100" ; int result = Integer.parseInt(s); System.out.println(result); System.out.println("------------------------------------------"); //String ---->Integer---->int //Constructor of Integer Integer(String s) //Member method of Integer: int intvalue() --- > int Integer integer = new Integer(s) ; int result2 = integer.intValue(); System.out.println(result2); } }
Character
Charcat: wrapper type of char type,
Main functions of Character
Main function name | Functional meaning |
---|---|
public static boolean isUpperCase(char ch) | Determines whether the current character is a capital letter character |
public static boolean isLowerCAse(char ch) | Is it a lowercase character |
public static boolean isDigit(char ch) | Is it a numeric character |
public static char toLowerCase(char ch) | Convert characters to lowercase |
public static char toUpperCase(char ch) | Convert characters to uppercase |
public class CharacterDemo { public static void main(String[] args) { //Create character class object Character character = new Character('a') ; // Character character = new Character((char)(97)) ; System.out.println(character); System.out.println("---------------------------------"); System.out.println("isUpperCase():"+Character.isUpperCase('A')); System.out.println("isUpperCase():"+Character.isUpperCase('a')); System.out.println("isUpperCase():"+Character.isUpperCase('0')); System.out.println("---------------------------------"); System.out.println("isLowerCase():"+Character.isLowerCase('A')); System.out.println("isLowerCase():"+Character.isLowerCase('a')); System.out.println("isLowerCase():"+Character.isLowerCase('0')); System.out.println("---------------------------------"); System.out.println("isDigit():"+Character.isDigit('A')); System.out.println("isDigit():"+Character.isDigit('a')); System.out.println("isDigit():"+Character.isDigit('0')); // char ch = 'a' ; // System.out.println(Character.toUpperCase(ch)); } }
Construction method of Character
Constructor name | Method meaning |
---|---|
public Character(char value) |
Character interview questions
- Requirements:
- Enter a character string with uppercase alphabetic characters, numeric alphabetic characters and lowercase alphabetic characters on the keyboard. Statistics are made separately regardless of other characters
- The number of uppercase alphabetic characters, lowercase alphabetic characters and numeric characters!
public class Test { public static void main(String[] args) { //Define three statistical variables int bigCount = 0 ; int smallCount = 0 ; int numberCount = 0; //Create keyboard entry object Scanner sc = new Scanner(System.in) ; //Prompt and enter data System.out.println("Please enter a data:"); String line = sc.nextLine() ; //Convert to character array char[] chs = line.toCharArray(); for (int i = 0; i <chs.length ; i++) { char ch = chs[i] ; /* //judge if(ch>='A' && ch<='Z'){ //capital bigCount ++ ; }else if(ch>='a' && ch<='z'){ //Lowercase letters smallCount ++ ; }else if(ch >='0' && ch<='9'){ numberCount ++ ; }*/ //Direct judgment if(Character.isDigit(ch)){ numberCount ++ ; }else if(Character.isUpperCase(ch)){ bigCount ++ ; }else if(Character.isLowerCase(ch)){ smallCount ++; } } System.out.println("Uppercase characters have"+bigCount+"individual"); System.out.println("Lowercase characters have"+smallCount+"individual"); System.out.println("Numeric characters have"+numberCount+"individual"); } }
Calendar: Calendar Class: Java util. Caldendar
Calendar: provides some field values such as obtaining the date of year, month and month. It is an abstract class and cannot be instantiated
public class CalendarDemo { public static void main(String[] args) { //Create calendar class object //Get the date of the system // Calendar c = new Calendar() ; //public static Calendar getInstance() Calendar calendar = Calendar.getInstance(); // System.out.println(calendar); //Acquisition year //public static final int YEAR int year = calendar.get(Calendar.YEAR) ; //Get month: //Public static final int month: between 0-11 int month = calendar.get(Calendar.MONTH) ; //Gets the date of the month //public static final int DATE //public static final int DAY OF MONTH: the first day of each month 1 int date = calendar.get(Calendar.DATE) ; System.out.println("Current calendar is:"+year+"year"+(month+1)+"month"+date+"day"); System.out.println("------------------------------------------------"); //Get 3 years ago today //Set the offset for year // public abstract void add(int field,int amount) // calendar.add(Calendar.YEAR,-3); //obtain // year = calendar.get(Calendar.YEAR) ; // System.out.println("current calendar is:" + year + "year + (month+1) +" month "+ date +" day "); } }
Static functions of the Calendar class
Static function name | Functional meaning |
---|---|
public static Calendar getInstance() | The return value is itself |
Member method of Calendar Class
Member method name | Method meaning |
---|---|
public int get(int field) | Get the value of the calendar field according to the given calendar field (system calendar) |
public abstract void add(int field,int amount) | Adds or subtracts the time offset to the specified calendar field |
Date: Date class: Java util. Date
Represents a specific moment, accurate to milliseconds!
It also allows you to format and parse date strings
Construction method of Date class
Constructor name | Method meaning |
---|---|
public Date() | Current system time format |
public Date(long date) | The parameter is the time millisecond value ----- > Date object (January 1, 1970...) |
public class DateDemo { public static void main(String[] args) { //Create date class object Date date = new Date() ; System.out.println(date); //Wed Jul 28 17:32:06 CST 2021 Date object System.out.println("------------------------"); long time = 60*60 ; Date date2 = new Date(time) ; System.out.println(date2); } }
DateFormat
Subclass providing specific date / format: SimpleDateFormat
Constructor for SimpleDateFormat
Constructor name | Function meaning |
---|---|
public SimpleDateFormat() | Use default mode |
public SimpleDateFormat(String pattern) | Use the specified pattern for parsing or formatting |
Date text - > date
public Date parse(String source)throws ParseException
//String - > date (key) //1) There is a date text format //2) Create a SimpleDateFormat object to specify a schema //3) Call parse method //Note: the SimpleDateFormat parsing pattern must match the String date text format String source = "2008-5-12" ; //Date text //Simpledateformat sdf2 = new simpledateformat ("MM dd, yyyy"); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd") ; //public Date parse(String source)throws ParseException Date dateResult = sdf2.parse(source); System.out.println(dateResult);
Date—>String
//Date - > string: format //1) Create Date object: represents the current system time object Date date = new Date() ; System.out.println(date); //2) Create SimpleDateForamt object: (intermediate bridge) SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ; //3) Call format: format String strDate = sdf.format(date); System.out.println(strDate);
DateUtils
This is for Java util. Date Date object and String: tool class for converting date text String to each other
public class DateUtils { //Construction method privatization private DateUtils(){} //Two static functions are provided //Date---->String /** * This method is for converting a date object to a date text string * @param date Date object to be formatted * @param pattern The specified mode is required * @return Returned date text string result yyyy MM DD */ public static String date2String(Date date,String pattern){ //Step by step //Create a SimpleDateFormat object /* SimpleDateFormat sdf = new SimpleDateFormat(pattern) ; String result = sdf.format(date); return result ;*/ //One step return new SimpleDateFormat(pattern).format(date) ; } //String -- > date: parsing process: parse(String source) throws ParseException /** * This method converts a String date text String into a date object * @param source Date text string to be parsed * @param pattern A pattern that needs to be used in parsing * @return The Date object returned is Date */ public static Date string2Date(String source,String pattern) throws ParseException { return new SimpleDateFormat(pattern).parse(source) ; } } public class Test { public static void main(String[] args) throws ParseException { //Direct use tool class //Date - > string format Date date = new Date() ; String str = DateUtils.date2String(date, "yyyy-MM-dd HH:mm:ss"); System.out.println(str); System.out.println("---------------------"); //String--->Date String source = "2022-6-9" ; Date date2 = DateUtils.string2Date(source, "yyyy-MM-dd"); System.out.println(date2); } }
Math: Math: Java lang.Math
For the tool class of mathematical operation, many methods are provided
Member method of Math class
Member method name | Method meaning |
---|---|
public static int abs(int a) | Absolute value method |
public static double ceil(double a) | Round up |
public static double floor(double a) | Round down |
public static int max(int a,int b) | Get maximum |
public static int min(int a,int b) | Get minimum value |
public static double pow(double a,double b) | b power of a |
public static double random() | [0.0,1.0): random number |
public static long round(double a) | rounding |
public static double sqrt(double a) | Open square root |
public class MathDemo { public static void main(String[] args) { //abs() System.out.println(Math.abs(-100)); // public static double ceil(double a): round up System.out.println(Math.ceil(13.56)); // public static double floor(double a): round down System.out.println(Math.floor(12.45)); // public static int max(int a,int b): get the maximum value System.out.println(Math.max(Math.max(10,30),50));//Method nesting //Public static double pow (double a, double b): power b of a System.out.println(Math.pow(2,3)); //Public static long round (double a): round System.out.println(Math.round(13.78)); // public static double sqrt(double a): open square root System.out.println(Math.sqrt(4)); } }
Random: pseudo random number generator: Java util. Random
Construction method of Random class
Constructor name | Method meaning |
---|---|
public Random() | Generate a random generator object. The random number is not different every time through the member method |
public Random(long seed) | The parameter is a value of long type (random number stream: seed). Each time the random number is obtained through the member method, the random number generated is the same |
Member method of Random class
Member method name | Method meaning |
---|---|
public int nextInt() | The range of the obtained value is the value range of int type (- 31st power of 2 to 31st power of 2 - 1) |
public int nextInt(int n) | Data obtained between 0-n (excluding n) |
Generate random number
- random method of Math class
public static double random(); - Random class: it can also be used
Parameterless construction method + member method
public Random():+ public int nextInt(int n)
public class RandomDemo { public static void main(String[] args) { //Create a random number generator // public Random(long seed) // Random random = new Random(1111) ; //The random number generated by the random number generator is different each time Random random = new Random() ; //Generate 10 numbers for(int x = 0 ; x < 10 ; x ++){ // public int nextInt(): // int num = random.nextInt(); //public int nextInt(int n) int num = (random.nextInt(30)+1); System.out.println(num); } } }
BigDecimal
Decimals should be calculated accurately - you can also calculate while retaining the number of significant digits after the decimal point
Construction method of BigDecimal
Constructor name | Method meaning |
---|---|
public BigDecimal(String value) | Numeric string |
Member method of BigDecimal
Member method name | Method meaning |
---|---|
public BigDecimal add(BigDecimal augend) | plus |
public BigDecimal subtract(BigDecimal subtrahend) | reduce |
public BigDecimal multiply(BigDecimal multiplicand) | ride |
public BigDecimal divide(BigDecimal divisor) | except |
public BigDecimal divide(BigDecimal divisor,int scale,int roundingMode) | Quotient, keep significant digits, round |
public class BigDecimalDemo { public static void main(String[] args) { //System.out.println(1.01 / 0.36); //Create BigDecimal object BigDecimal bg1 = new BigDecimal("1.01") ; BigDecimal bg2 = new BigDecimal("0.36") ; System.out.println("------------------------------------"); BigDecimal bg3 = new BigDecimal("10.0") ; BigDecimal bg4 = new BigDecimal("5.05") ; System.out.println(bg1.add(bg2)); System.out.println(bg1.subtract(bg2)); System.out.println(bg1.multiply(bg2)); // System.out.println(bg3.divide(bg4));// Not retained (divisible) System.out.println(bg3.divide(bg4,3,BigDecimal.ROUND_HALF_UP));//Forty five in } }
object array
An array that can store objects
Requirements:
- Use the array to store 5 students (name, age, gender), and then traverse the array to get the information of each student
public class Student { private String name ; private int age ; private String gender ; public Student() { } public Student(String name, int age, String gender) { this.name = name; this.age = age; this.gender = gender; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + ", gender='" + gender + '\'' + '}'; } } public class ObjectArrayDemo { public static void main(String[] args) { //Create student array // Data type [] array name = new data type [length]; Student object array Student[] students = new Student[5] ; //Create 5 students Student s1 = new Student("article",35,"male") ; Student s2 = new Student("Gao Yuanyuan",42,"female") ; Student s3 = new Student("Liu Yifei",33,"female") ; Student s4 = new Student("Ma Rong",30,"female") ; Student s5 = new Student("Ma Baoguo",65,"male") ; //Assign values to elements in the array students[0] = s1 ; students[1] = s2 ; students[2] = s3 ; students[3] = s4 ; students[4] = s5 ; //Traverse student array for(int x = 0 ; x < students.length ; x ++){ //System.out.println(students[x]); //You need to get the member information with the getXXX() method Student s = students[x] ; System.out.println(s.getName()+"---"+s.getAge()+"---"+s.getGender()); } } }
Collection
Set level root interface
Some collections allow element repetition (List), and some collections do not allow element repetition (Set)
Some collections are ordered (consistent storage and retrieval) (List), and some collections are disordered (inconsistent storage and retrieval) (Set)
The JDK does not provide any direct implementation of this interface: it provides more specific implementations of sub interfaces, such as Set and List
Collection's most specific subclass implementation
ArrayList
LinkedList
Vector
Basic functions of Collection
Basic function name | Functional meaning |
---|---|
boolean add(Object e) | Add element E(Element) |
void clear() | Violent deletion (kill all elements of the collection) |
boolean remove(Object o) | Deletes the specified element from the collection |
int size() | Gets the number of elements in the collection |
boolean isEmpty() | Judge whether the collection is empty. If it is an empty element, return true |
boolean contains(Object o) | Judge whether the collection contains the specified element, and return true if it does |
Object[] toArray() | The collection was converted to an array of objects |
public class CollectionDemo { public static void main(String[] args) { //Create Collection collection object //Interface polymorphism Collection c = new ArrayList() ; System.out.println(c);//ArrayList overrides the toString() method of Object System.out.println("-----------------------------------------"); // boolean add(Object e): add element E(Element) // boolean flag = c.add("hello"); /** * Original code added * public boolean add(E e) { * ensureCapacityInternal(size + 1); // Increments modCount!! * elementData[size++] = e; * return true; //Always return true * } */ //System.out.println(flag); c.add("hello") ; c.add(100) ; c.add("javaee") ; System.out.println(c); // void clear() // c.clear(); // boolean remove(Object o): deletes the specified element from the collection // System.out.println(c.remove(100)); //int size() System.out.println(c.size()); System.out.println("--------------------------"); System.out.println(c.contains("world")); System.out.println(c.contains("javaee")); System.out.println(c.isEmpty()); System.out.println(c); } }
Advanced features of Collection
Advanced feature name | Functional meaning |
---|---|
boolean addAll(Collection c) | Add all elements in a collection |
boolean containsAll(Collection c) | Contains all elements in a collection |
boolean removeAll(Collection c) | Delete all elements in the collection |
boolean retainAll(Collection c) | Intersection of A set and B set |
public class CollectionDemo2 { public static void main(String[] args) { //Create two Collection collection objects Collection c1 = new ArrayList() ; c1.add("abc1") ; c1.add("abc2") ; c1.add("abc3") ; c1.add("abc4") ; /* c1.add("abc5") ; c1.add("abc6") ; c1.add("abc7") ;*/ /* c1.add("abc5") ; c1.add("abc6") ; c1.add("abc7") ;*/ Collection c2 = new ArrayList() ; c2.add("abc1") ; c2.add("abc2") ; c2.add("abc3") ; c2.add("abc4") ; c2.add("abc5") ; c2.add("abc6") ; c2.add("abc7") ; System.out.println(c1); System.out.println(c2); System.out.println("---------------------------------"); //boolean addAll(Collection c): adds all elements in a collection // System.out.println(c1.addAll(c2)); //boolean containsAll(Collection c): contains all elements // System.out.println(c1.containsAll(c2)); //boolean removeAll(Collection c): delete all elements in the collection (delete one or all): delete one or all elements (must be included at the same time) // System.out.println(c1.removeAll(c2)); // boolean retain all (collection C): set A finds the intersection of set B. what does the return value of boolean mean, and whether the elements of the intersection are saved in A or B /** * A Find the intersection of set B in the set heap. The elements of the intersection are stored in set A, and then return the value. It means to see whether the elements of set A have changed (compare the previous elements with the elements of the current intersection) * If there is any change, return true; If there is no change, false is returned * */ System.out.println(c1.retainAll(c2)); //The intersection of c1 set and c2 set System.out.println(c1); System.out.println(c2); System.out.println("-------------------------------------------"); //Use the Collection to store 5 students (name, age, gender), and then traverse the Collection to get the information of each student! //Create a Collection collection object Collection c = new ArrayList() ; //Create 5 students Student s1 = new Student("Song Jiang",45,"male") ; Student s2 = new Student("Li Kui",35,"male") ; Student s3 = new Student("Wu Dalang",35,"male") ; Student s4 = new Student("ximen qing",30,"male") ; Student s5 = new Student("Wu Yong",40,"male") ; //Stored in collection c.add(s1) ; c.add(s2) ; c.add(s3) ; c.add(s4) ; c.add(s5) ; // Object[] toArray(): converted the collection into an object array Object[] objs = c.toArray();//Each data type stored in the array Object obj = new Student()// Upward transformation //Traversal array for(int x = 0 ; x < objs.length ; x ++){ //System.out.println(objs[x]) ; //Getxxx() --- > method of student class Student student = (Student) objs[x]; //Downward transformation System.out.println(student.getName()+"---"+student.getAge()+"---"+student.getGender()); } } }
Generic < E / T >
Collection type < reference data type > collection object name = new subclass < reference data type > ();
Benefits of generics:
- 1) The runtime exception was advanced to compile time
- 2) Casts are avoided
- 3) Improved program security
public class GenericDemo { public static void main(String[] args) { //Create Collection collection object Collection<String> c = new ArrayList<String>() ; //New XXX < < data type >: JDK7 later generic inference c.add("hello") ; c.add("Gao Yuanyuan") ; c.add("how are you") ; // c.add(100) ; //Get iterator iterator < E > is consistent with the generics stored in the collection Iterator<String> it = c.iterator(); while(it.hasNext()){ //Get the length as well as the String String str = it.next(); System.out.println(str+"---"+str.length()); } } }
Collection interview questions
What's the difference between a set and an array?
- 1) Length difference
Array: fixed length
Sets: variable length - 2) Differences between storage data types
Array:
You can store basic data types or reference data types
int[] arr = {100,200,50,“hello”} ; No
Set: precondition: adding generic types to the set is also a feature of analog array:
Only reference type Collection can be stored: generic < reference type > - 3) Differences between storage elements:
Array: stored elements must be of the same data type
Collection: if you do not add generics: elements of any type (must reference types)
Iterator for Collection
Proprietary traversal of collections
Iterator
Iterator iterator(): return value type, interface type, sub implementation class object to be returned
Iterator interface
Iterator interface name | Interface meaning |
---|---|
boolean hasNext() | Determines whether the next element exists in the iterator |
Object next() | Gets the next element that can be traversed |
public class CollectionTest { public static void main(String[] args) { //Create collection object Collection c = new ArrayList() ; //Sub implementation class of List interface (duplicate element) //Add element c.add("hello") ; c.add("world") ; c.add("javaee") ; // System.out.println(c); //Gets the Iterator iterator() of the Collection Iterator it = c.iterator(); //If three elements are explicitly stored now, these data may be a list collection data obtained from the database in the future. Generally, the while loop while(it.hasNext()){//Determine whether there is the next element in the iterator //Just get Object obj = it.next();// Object obj = new String("hello") ... // System.out.println(obj+"----"+obj.length()); //At the same time, get the length of the current storage element ----- > string type length() String str = (String) obj;//Downward transformation System.out.println(str+"----"+str.length()); } } }
Iterator interview questions
Use the Collection to store 4 students (name and age), and then use the Iterator iterator()
public class CollectionTest2 { public static void main(String[] args) { //Create collection object Collection c = new ArrayList(); //Create 4 students Student s1 = new Student("Zhuge Liang",45) ; Student s2 = new Student("Pang Tong",30) ; Student s3 = new Student("Zhou Yu",35) ; Student s4 = new Student("Lv Bu",25) ; c.add(s1) ; c.add(s2) ; c.add(s3) ; c.add(s4) ; //Get iterator Iterator iterator = c.iterator(); while(iterator.hasNext()){ Object obj = iterator.next(); // System.out.println(obj); // String s = (String)obj ; Student s = (Student)obj ; System.out.println(s.getName()+"---"+s.getAge()); } } }
List
List set features:
- Ordered (storage element and extraction element are consistent)
- Allow element duplication
Unique features of the List collection
Unique function name | Functional meaning |
---|---|
void add(int index,Object element) | Inserts an element at the specified index |
Object get(int index) | Gets the element at the specified location |
Object remove(int index) | Deletes the element at the specified location |
Object set(int index,E element) | Object set(int index,E element) |
ListIterator listIterator() | List iterator |
public class ListDemo { public static void main(String[] args) { //Create a List collection object List<String> list = new ArrayList<String >(); //Add element list.add("hello") ; list.add("hello") ; list.add("world") ; list.add("world") ; list.add("world") ; list.add("javaEE") ; list.add("javaEE") ; // void add(int index,Object element): inserts an element at the specified index list.add(1,"Gao Yuanyuan"); //Object get(int index): get the element at the specified location: the returned content of the obtained element System.out.println(list.get(1)); // Object remove(int index): deletes the element at the specified position and returns the deleted element System.out.println(list.remove(2)); System.out.println("---------------------------------------"); //Object set(int index,E element): modify the element at the specified position (replace) System.out.println(list.set(1,"You Ting Zhao")); System.out.println(list); } }
Traversal of the List collection
- Object[] toArray()
- Iterator iterator()
- Object get(int index): get the element at the specified position + int size(): a new collection traversal method
public class ListTest { public static void main(String[] args) { //Create a List collection object List<String> list = new ArrayList<>() ; //Add element list.add("hello"); list.add("world"); list.add("java"); list.add("android"); //size()+get(int index) set for(int x = 0 ; x < list.size() ; x ++){ String s = list.get(x); System.out.println(s+"---"+s.length()); } System.out.println("-----------------------------------------------"); //The List collection stores the Student object and traverses it (Student: name, age) List<Student> stuList = new ArrayList<>() ;//Generic inference after JDK7: automatically consistent with the previous generic types! //Create 3 students Student s1 = new Student("Zhang Jianing",31) ; Student s2 = new Student("Delireba",29) ; Student s3 = new Student("Zhang Junjie",20) ; //Add to list stuList.add(s1) ; stuList.add(s2) ; stuList.add(s3) ; //ergodic //Method 1:Object[] toArray() Object[] objs = stuList.toArray(); for(int x = 0 ; x < objs.length ; x ++){ Student s = (Student) objs[x]; System.out.println(s.getName()+"----"+s.getAge()); } System.out.println("--------------------------------------"); //Iterator for Collection Iterator<Student> it = stuList.iterator(); while(it.hasNext()){ Student s = it.next() ; System.out.println(s.getName()+"---"+s.getAge()); // System.out.println((it.next().getName()+"---"+(it.next().getAge()))); // next() can only be used once and cannot be used more than once / / incorrect usage } System.out.println("-------------------------------------"); //Method 3:size()+get(int index) for(int x = 0 ; x < stuList.size() ; x ++){ Student s = stuList.get(x); System.out.println(s.getName()+"----"+s.getAge()); } System.out.println("-----------------------------------------"); //Forward traversal: listiterator < E > listiterator(): List iterator: List collection specific traversal method ListIterator<Student> lit = stuList.listIterator(); /** * ListIterator extends Iterator{} * * class ArrayList{ * List The specific ArrayList subclass overrides Iterator listiterator(){ * * return new ListItr(0) ; * } * * private class ListItr extends Itr implements Iterator{ * * //hasNext() * //next() * } * * } */ while(lit.hasNext()){ Student student = lit.next(); System.out.println(student.getName()+"---"+student.getAge()); } System.out.println("-----------------------------------------"); //Reverse traversal: premise: there must be forward traversal //ListIterator<E> listIterator() //ListIterator: unique features: //boolean hasPrevious(): whether there is a previous element that can be iterated //Object previous(): get the previous element while(lit.hasPrevious()){ Student student = lit.previous(); System.out.println(student.getName()+"---"+student.getAge()); } } }
How to de duplicate
Storage string type
New method: empty set
//Create an empty collection List List<String> newList = new ArrayList<>() ; //Traverse previous collections for(String s :list){ //Use the new set to judge that the element is not included, indicating that the element is not repeated, and you can add it if(!newList.contains(s)){ newList.add(s) ; } } //Traverse the new collection for(String s:newList){ System.out.println(s); }
Method 2: use the idea of selective sorting to complete
//Using the idea of selective sorting for(int x = 0 ; x < list.size()-1 ; x ++){ for(int y = x +1 ; y < list.size() ; y++){ //If the following element is the same as the previous element if(list.get(y).equals(list.get(x))){ //remove through collection list.remove(y) ; // public Object remove(int index) //Angle mark-- y -- ; } } } for(String s:list){ System.out.println(s); }
Store custom objects
- Method 1: new collection idea
The contains(Object) method depends on the equals method of the Object, so the class of the type stored in the collection must override the equals method, otherwise it is used by default - Method 2: rewrite the duplicate student objects stored in the List using the idea of selective sorting!
//Method 1: create a new collection List<Student> newList = new ArrayList<>() ; //Traverse the previous collection to get each student object for(Student s:list){ //If the current newList does not contain this student, add it to the new collection if(!newList.contains(s)){ newList.add(s) ; } } //Traverse new set for(Student student:newList){ System.out.println(student.getName()+"----"+student.getAge()); }
List interview questions
Requirements:
- Through the ArrayList collection object of the List collection, if there is a "world" element in the current collection, add a "javaEE" element to the collection, and finally traverse all the elements in the collection!
Concurrent modification exception of List Java util. ConcurrentModificationException
Problems that often occur when using iterators for Collections: concurrent modification exceptions,
- When the elements of a collection are being traversed by the iterator, the collection object cannot add or delete elements (a thread is traversing and a thread is modifying elements)
- Solution:
1) Either the iterator goes through the elements of the collection and the iterator adds elements: the list iterator has the action of adding
2) Either traverse the collection or add the collection
public class ListTest2 { public static void main(String[] args) { //Create a List collection object List<String> list = new ArrayList<>() ; //Add element to list.add("hello") ; list.add("world") ; list.add("javaee") ; //Traversal using iterators //Iterator iterator() /* Iterator<String> it = list.iterator(); //"hello","world","javaee" while(it.hasNext()){ String s = it.next() ;//"hello","world","javaee" //judge if("world".equals(s)){ list.add("javaEE") ;//The iterator does not know the element added to the collection object } } System.out.println(list);*/ //Solution 1: 1) either the iterator traverses the elements of the collection and the iterator adds elements: the list iterator has the action of adding //ListIterator //void add(E e) /*ListIterator<String> lit = list.listIterator(); while(lit.hasNext()){ //obtain String s = lit.next(); //Determine whether there is a "world" element if("world".equals(s)){ //List iterator add lit.add("javaEE"); } }*/ //Scheme 2: either traverse the collection or add the collection //size()+get(int index) for(int x = 0 ; x < list.size(); x ++){ String s = list.get(x); if("world".equals(s)){//Put constants first to prevent NullPointerException list.add("javaEE"); } } System.out.println(list); } }
Vector
Vector set specific functions
Unique function name | Functional meaning |
---|---|
public void addElement(Object obj) | Add an element at the end of the vector object |
public boolean removeElement(Object obj) | Delete element |
public Object elementAt(int index) | Gets the element at the specified location |
boolean hasMoreElements() | Determine whether more elements can be iterated |
Object nextElement() | Get element |
Traversal method of Vector set
Traversal method name | |
---|---|
public Enumeration elements() | Proprietary traversal of Vector sets |
public class VectorDemo { public static void main(String[] args) { //Create Vector collection object Vector<String> v = new Vector<>() ; v.addElement("hello"); v.addElement("world"); v.addElement("SpringBoot"); v.addElement("SpringCloud") ; //Traversal: unique functions Enumeration<String> en = v.elements(); //Equivalent to Iterator while(en.hasMoreElements()){ String s = en.nextElement(); System.out.println(s+"---"+s.length()); } System.out.println("----------------------------------"); for(String s: v){ System.out.println(s+"----"+s.length()); } } }
Enhanced for loop
Replace the iterator in the collection to traverse the collection (priority is given to use in the collection)
- Format:
For (stored reference data type variable name: set / array object){
//Collections are mostly used, and arrays generally use ordinary for
Just use the variable name
} - matters needing attention:
The current collection object cannot be null: foreach statement: enhancing for itself is to obtain the iterator, and a null pointer exception will occur
public class ForeachDemo { public static void main(String[] args) { //array int[] arr = {11,22,33,44,55} ; for(int x = 0 ; x < arr.length ; x ++){ System.out.println(arr[x]); } System.out.println("--------------------------------"); /* for(Stored reference data type (variable name: collection / array object){ * Just use the variable name * } */ //For arrays: use normal for /* for(int a:arr){ System.out.println(a); }*/ //Create List collection List<String> list = new ArrayList<>() ; list.add("hello") ; list.add("world") ; list.add("javaee") ; /* for(String s:list){//Replace iterator use //If the world element exists, add an android element //System.out.println(s); if("world".equals(s)){ list.add("android") ;//Concurrent modification exception occurred } } System.out.println(list); */ list = null ; if(list!=null){ for(String s:list){//Get iterator System.out.println(s+"---"+s.length()); } }else{ System.out.println("The current collection object is null Yes"); } } }
Enhanced for round robin interview questions
- Requirements:
Use enhanced for to traverse the List, store three students, and obtain student information (name and age) after traversal
public class ForeachTest { public static void main(String[] args) { //Create List List<Student> list = new ArrayList<>() ; //Create three students Student s1 = new Student("Zhang Jianing",29) ; Student s2 = new Student("Deng Chao",40) ; Student s3 = new Student("Hai Bo Huang",30) ; list.add(s1) ; list.add(s2) ; list.add(s3) ; //Mode 5: enhanced for loop for (Student s: list) { // System.out.println(s.getName()+"---"+s.getAge()); System.out.println(s); //Object name: directly use the rewritten toString() } } }
Insert sort
- Core idea: use the elements corresponding to the 1 subscript to compare with the 0 subscript
If the front element is large, move it to the right to determine the position of the element corresponding to corner mark 1, and then use the element corresponding to corner Mark 2 to compare with both 1 and 0 elements in turn
Compare this in turn
public class InsertSortTest { public static void main(String[] args) { //Define an Integer array: natural sorting implemented by Integer: elements can be sorted in ascending order by default Integer[] arr = {34,8,64,51,32,21} ; System.out.println("Before sorting:"); printArr(arr); //Define a function insertSort(arr) ; System.out.println("After sorting:"); printArr(arr); } //Insert sort private static void insertSort(Integer[] arr) { //Define a variable j int j ; //j record the change of the current angle mark //p = 1,5: the number of times each element is moved for(int p = 1 ; p < arr.length ; p ++ ){ //Comparison times p=2 //Define temporary variable temp Integer temp = arr[p] ; //temp = 8; temp = 64 //Start comparison for(j = p ; j>0 && temp.compareTo(arr[j-1])<0; j-- ){ // j= 1 ; 1>0&& 8 < 34 j-- : j= 0 //j=2 ; 2>0 && 64 < 32 //Data movement arr[j] = arr[j-1] ; } //Determine the position of temp: position of 8 position of 64 position: p=2 arr[j] = temp ; // No move } } public static void printArr(Integer[] arr){ System.out.print("["); for(int x = 0 ; x < arr.length ; x ++){ if(x == arr.length -1){ System.out.println(arr[x] +"]"); }else{ System.out.print(arr[x]+", "); } } } }