1, toString method of Object class
- java.Lang.object
- Class object is the root (parent) class of the class hierarchy.
- Each class (person, student...) All use object as the super (parent) class. All objects (including arrays) implement the methods of this class.
public class Person { private String name; private int age; public Person() { } public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; }
public static void main(string[]args) { /* Person Class inherits the object class by default, so you can use the toString method string tostring() in the object class to return the string representation of the object. */ Person p = new Person( name:"Zhang San",age: 18); String s = p.tostring(); system.out.println(s);//com.zhang.0bject.Person@75412c2f Person(nome=Zhang San,age=18) //Directly print the name of the object, which is actually the toString p=p.toString(); system.out.println(p);//com.zhang.object.Person@5f150435 PersonP(noamen Zhang San,oge=18) }
Note: to see whether a class rewrites toString, print the object of this class directly. If the toString method is not rewritten, the address value of the object is printed
2, equals method of Object class
Use the equals method of the object class
boolean equals(object obj) indicates whether some other object is "equal" to this object.
equals Method source code: public boolean equals(0bject obj) { return (this == obj); }
Parameters:
- 0object obj: any object can be passed
- ==The comparison operator returns a Boolean value of true false. Basic data type: the comparison is the value reference data type: the price comparison is the address value of two objects
- Who is this? The method called by that object, and this in the method is that object;
3, Override the equals method of the Object class
The equals method of object class compares the address values of two objects by default, which is meaningless. Therefore, we need to override the equals method to compare the properties (name, age) of two objects
Question:
- Implies a polymorphism
- Disadvantages of polymorphism: you can't use the content (attributes and methods) specific to subclasses. Object = P2 = new Person ("Xiaomei", 19); solution: you can use downward transformation (strong transformation) to convert the obj ect type to Person
@Override public boolean equals(0bject obj) { //Add a judgment. If the parameter obj passed is this itself, it will directly return true to improve the efficiency of the program if(obj==this){ return true; } //Add a judgment. If the passed parameter obj is null, it will directly return false to improve the efficiency of the program if(obj==null){ return false; } //Add a judgment to prevent the type conversion from cLasscastException once if(obj instanceof Person){//Judge whether the parameter obj is of person type //Use the downward transformation to convert obj to Person type erson p = (Person)obj; //Compare the properties of two objects. One object is this (who calls this is this), and the other object is p(obj) boolean b = this.name.equals(p.name) &&this.age==p.age; return b; } //Return false if it is not a person type return false; }
3.1. equals method of Objects class
equals method of objects class: compare two objects to prevent null pointer exceptions
public static boolean equals(0bject a, 0bject b) { return (a == b) il ( a != null && a.equals(b)); } //demonstration boolean b2 = Objects.equals(s1,s2); system.out.print1n(b2);
4, Date class
- java.util.Date: a class representing date and time. Date represents a specific moment, accurate to seconds. Milliseconds: thousandth of a second 1000 milliseconds = 1 second
- The function of millisecond value: it can calculate the time and date
- How many days are there between 2099-01-03 and 2088-01-61
- You can change the date into milliseconds for calculation. After calculation, you can convert milliseconds into dates
- Convert milliseconds to date: 1 day = 24 x 60 x 60 = 86400 seconds = 86400 x 1000 = 86400008 milliseconds
public static void main(String[]args) { //How many milliseconds did it take to get the current system time from 00:00:60 on January 1, 1970 system.out.printIn(System.currentTimeillis()); }
5, DateFormat class and SimpleDateFormat
- java.text.DateFormat: is an abstract class of date / time formatting subclass
- Function: format (i.e. date - > text), parse (text - > date)
Member method:
- string format(Date date) formats the date date into a string matching the pattern according to the specified pattern. Date parse(String source) parses the string matching the pattern into a date date
- DateFormat class is an abstract class and cannot be used to create objects directly. You can use the subclass of DateFormat class
java.text.SimpleDateFormat extends DateFormat
Construction method:
- SimpLeDateFormat(string pattern)
Construct simpleDateFormat with the given pattern and date format symbol of black f recognition locale.
Parameters:
String pattern: pass the specified pattern:
Case sensitive
y year, m month, d day, H hour, m minute, s second
second
Write the corresponding mode, and the mode will be replaced with the corresponding date and time
- "yyyy-MMM-dd HH : mm : SS""
be careful:
The letters in the mode cannot be changed, and the symbols of the connection mode can be changed
- "yyyy dd mm / dd H h mm min ss s"“
Convert time and date to the corresponding format:
public static void main(String[ ] args) { demoe1(); /** Using the method format in the DateFormat class, To format a date as text: 1.Create a SimpLeDateFormat object and pass the specified pattern in the constructor 2.Call the method format in the simpleDateFormat object to format the pate date into a string (text) that conforms to the pattern according to the pattern specified in the construction method */ private static void demoe1() { //1. Create a SimpleDateFormat object and pass the specified pattern in the constructor simpleDateFormat sdF = new simpleDateFormat("yyyy years dd day H Time mm branch ss second"); //2. Call the method format in the SimpLeDateFormat object and format the Date date into a string (text) conforming to the pattern according to the pattern specified in the construction method //Sstring format(Date date) formats the Date date into a string conforming to the specified pattern Date ri= new Date(; string time= sdf.format(ri); System.out.println("Before conversion:"+ri); //Before conversion: Fri Apr 09 14:11:14 CST 2021 System.out.println("After formatting:"+time);//After formatting: 14:11:14 on April 9, 2021 } }
The corresponding text format is converted to date
public static void main(String[ ] args) throws ParseException { demoe2(); /*Use the method parse in the DateFormot class, To parse text into date, use the following steps: 1 .Create a SimpleDateFormat object and pass the specified pattern in the constructor 2.Call the parse method in the SimpleDateFormat object to parse the string that conforms to the pattern in the construction method into a Dote date. Note public Date parse(String source) throws ParseExceptionparse Method declares an exception called ParseException If the pattern of string and constructor is different, the program will throw this exception When calling a method that throws an exception, you must handle the exception. Either throw continues to throw the exception, or try catch handles it by itself */ private static void demoe2()throws ParseException { //1. Create a SimpleDoteFormat object and pass the specified pattern in the construction method SimpleDateFormat sdf m new SimpleDateFormat( patterm:"yyyy year A month dd day H Time mm branch ss second"); //2. Call the method pars in the SimpLeDateFormat object to parse the string that conforms to the pattern in the construction method into a Date date // /Date parse(String source) parses the string that conforms to the pattern into a date date Date date = sdf.parse( source:"2021 At 14:11:14 on April 9"); System.out.print1n(date);//Fri Apr 09 14:11:14 CST 2021 } }
6, Introduction to Calendar Class
- java.util.calendar Class: Calendar Class
- Calendar class is an abstract class, which provides many methods to operate calendar fields (YEAR, MONTH, DAY_OF_NONTH, HOUR)
- The caLendar class cannot create objects directly. There is a static method called getInstance(), which returns subclass objects of the caLendar class
- static calendar getInstance() obtains a calendar using the de f ault time zone and locale.
7, Common methods of System class
java. The lang.system class provides a large number of static methods to obtain system related information or system level operations. In the API documents of the 5system class, the common methods are:
- public static long currentTimeNMillis(): returns the current time in milliseconds.
- public static void arraycopy(Object src,int srcPos,Object dest,int
destPos, int length): copy the data specified in the array to another array.
The value of milliseconds consumed while the validator is running
public class Test { public static void main(String[] args) { atime(); } /** * The number of milliseconds consumed in the validation cycle is 9999-9991 */ private static void atime() { //Get the millisecond value once before program execution long start = System.currentTimeMillis(); for (int i = 0; i <= 9999; i++) { System.out.println(i); } //Get the millisecond value once after the program execution is completed long end = System.currentTimeMillis(); System.out.println("Total program time"+(end-start)+"millisecond");//The program takes 58 milliseconds }
8, StringBuilder class
String buffer can improve the operation efficiency of string (as a string with variable length). The bottom layer is also an array, but it is not modified by final, and the length can be changed
- java.Lang. StringBuiLder class: string buffer, which can improve the efficiency of strings
Construction method:
- stringBuilder() constructs a string generator without any characters, with an initial capacity of 16 characters.
- stringBuilder (String str) constructs a string generator and initializes it to the specified string content.
public static void main(String[]args){ //Null parameter construction method stringBuilder bu1 = new stringBuilder(); system.out.println( "bu1 :"+bu1);//bu1 : /Construction method with string stringBuilder bu2 = new StringBuilder( "abc" ); System.out.println( ""bu2 : "+bu2);//bu2:ABC }
StringBuilder and string can be converted to each other:
- string becomes stringBuilder: you can use the construction method of stringBuilder
- StringBuilder(String str) constructs a string generator and initializes it to the specified string content.
- Stringbuild becomes String: you can use the tostring method in StringBuilde r
- public string tostring(): converts the current stringBuilder object into a string object.
public static void main(string[]args) { // String becomes StringBuilder string str = "hel1o"; System.out.println( "str: "+str); stringBuilder bu = new StringBuilder( str); //Add data to stringBuilder bu.append( "world" ) ; system.out.println("bu:"+bu) ;/ / StringBuilder->String String s = bu.toString(); system.out.println( "s: " +s ); }