Object class, common API

Chapter 1 Object class

1.1 general

java.lang.Object class is the root class in the Java language, that is, the parent class of all classes. All method subclasses described in it can be used. When an Object is instantiated, the final parent class is Object.

If a class does not specify a parent class, it inherits from the Object class by default. For example:

public class MyClass /*extends Object*/ {
  	// ...
}

According to the JDK source code and the API documents of the Object class, the Object class contains 11 methods. Today we mainly learn two of them:

  • public String toString(): returns the string representation of the object.
  • public boolean equals(Object obj): indicates whether another object is "equal" to this object.

1.2 toString method

Method summary

  • public String toString(): returns the string representation of the object.

The toString method returns the string representation of the object. In fact, the string content is the type + @ + memory address value of the object.

Since the result returned by the toString method is the memory address, it is often necessary to get the corresponding string representation according to the object properties in development, so it also needs to be rewritten.

Overwrite

If you do not want to use the default behavior of the toString method, you can override it. For example, the customized Person class:

public class Person {  
    private String name;
    private int age;

    @Override
    public String toString() {
        return "Person{" + "name='" + name + '\'' + ", age=" + age + '}';
    }

    // Omit constructor and Getter Setter
}

In IntelliJ IDEA, click Generate... In the Code menu, You can also use the shortcut key alt+insert and click the toString() option. Select the member variables to include and confirm. As shown in the figure below:

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-fhuzcx4v-1624549048189) (automatic rewriting of img \ toString method. bmp)]

Tip: when we directly use the output statement to output the object name, we actually call its toString() method through the object.

1.3 equals method

Method summary

  • public boolean equals(Object obj): indicates whether another object is "equal" to this object.

If you call the member method equals and specify another object as the parameter, you can judge whether the two objects are the same. The "same" here has two methods: default and user-defined.

Default address comparison

If the equals method is not overridden, the Object address comparison of the = = operator is performed by default in the Object class. As long as it is not the same Object, the result must be false.

Object content comparison

If you want to compare the contents of objects, that is, if all or some of the specified member variables are the same, you can override the equals method. For example:

import java.util.Objects;

public class Person {	
	private String name;
	private int age;
	
    @Override
    public boolean equals(Object o) {
        // If the object addresses are the same, they are considered the same
        if (this == o)
            return true;
        // If the parameter is empty or the type information is different, it is considered different
        if (o == null || getClass() != o.getClass())
            return false;
        // Convert to current type
        Person person = (Person) o;
        // The basic types are required to be equal, and the reference type is given to Java util. The equals static method of the objects class fetches the result
        return age == person.age && Objects.equals(name, person.name);
    }
}

This Code fully considers the problems of empty object and consistent type, but the method content is not unique. Most ides can automatically Generate the Code content of the equals method. In IntelliJ IDEA, you can use the Generate... Option in the Code menu, or you can use the shortcut key alt+insert and select equals() and hashCode() to Generate Code automatically. As shown in the figure below:

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-9FlHNltG-1624549048193)(img\equals method 1.png)]

[the external chain picture transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (IMG dkniwdhy-1624549048196) (IMG \ equals method 2.png)]

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-189B92rp-1624549048199)(img\equals method 3.png)]

tips: hashCode and other methods in the Object class. Learn from now on.

1.4 Objects class

In the automatic rewriting of equals code by IDEA just now, Java util. Objects class, so what is this class?

An Objects tool class is added in JDK7. It provides some methods to operate Objects. It consists of some static practical methods. These methods are null save (null pointer safe) or null tolerance (null pointer tolerant), which are used to calculate the hashcode of the object, return the string representation of the object, and compare the two Objects.

When comparing two Objects, the equals method of Object is easy to throw null pointer exceptions, and the equals method in the Objects class optimizes this problem. The method is as follows:

  • public static boolean equals(Object a, Object b): judge whether two objects are equal.

We can check the source code and learn:

public static boolean equals(Object a, Object b) {  
    return (a == b) || (a != null && a.equals(b));  
}

Chapter II date time category

2.1 Date class

summary

java. util. The date class represents a specific moment, accurate to milliseconds.

Continue to refer to the description of the Date class. It is found that Date has multiple constructors, but some of them are outdated, but some of them can convert the millisecond value into a Date object.

  • public Date(): allocates a Date object and initializes it to represent the time (in milliseconds) at which it was allocated.
  • public Date(long date): allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time (called epoch), i.e. 00:00 GMT, January 1, 1970).

tips: since we are in the East eighth District, our benchmark time is 8:0:0 on January 1, 1970.

To put it simply: using the nonparametric structure, you can automatically set the millisecond time of the current system time; Specify the construction parameters of long type, and you can customize the millisecond time. For example:

import java.util.Date;

public class Demo01Date {
    public static void main(String[] args) {
        // Create a date object and put the current time
        System.out.println(new Date()); // Tue Jan 16 14:37:35 CST 2018
        // Create a date object and convert the current millisecond value into a date object
        System.out.println(new Date(0L)); // Thu Jan 01 08:00:00 CST 1970
    }
}

tips: when using the println method, the toString method in the Date class will be called automatically. The Date class overrides the toString method in the Object class, so the result is a string in the specified format.

common method

Most of the methods in the Date class are outdated. The common methods are:

  • public long getTime() converts the date object to the corresponding time millisecond value.

2.2 DateFormat class

java.text.DateFormat is an abstract class of date / time formatting subclass. Through this class, we can help us complete the conversion between date and text, that is, we can convert back and forth between Date object and String object.

  • Format: convert from Date object to String object according to the specified format.
  • Parsing: converts a String object to a Date object in the specified format.

Construction method

Because DateFormat is an abstract class and cannot be used directly, it needs a common subclass Java text. SimpleDateFormat. This class requires a schema (format) to specify the standard for formatting or parsing. The construction method is:

  • public SimpleDateFormat(String pattern): construct SimpleDateFormat with the date format symbols of the given schema and default locale.

The parameter pattern is a string representing the custom format of date and time.

Format Rules

Common format rules are:

Identification letters (case sensitive)meaning
yyear
Mmonth
dday
HTime
mbranch
ssecond

Note: for more detailed format rules, please refer to the API document 0 of SimpleDateFormat class.

The code to create the SimpleDateFormat object is as follows:

import java.text.DateFormat;
import java.text.SimpleDateFormat;

public class Demo02SimpleDateFormat {
    public static void main(String[] args) {
        // Corresponding date format: 2018-01-16 15:06:38
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }    
}

common method

The common methods of DateFormat class are:

  • public String format(Date date): formats the Date object as a string.
  • public Date parse(String source): parses a string into a Date object.

format method

The code using the format method is:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
 Convert Date object to String
*/
public class Demo03DateFormatMethod {
    public static void main(String[] args) {
        Date date = new Date();
        // Create a date format object. You can specify the style when obtaining the format object
        DateFormat df = new SimpleDateFormat("yyyy year MM month dd day");
        String str = df.format(date);
        System.out.println(str); // January 23, 2008
    }
}

parse method

The code to use the parse method is:

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
 Convert String to Date object
*/
public class Demo04DateFormatMethod {
    public static void main(String[] args) throws ParseException {
        DateFormat df = new SimpleDateFormat("yyyy year MM month dd day");
        String str = "2018 December 11";
        Date date = df.parse(str);
        System.out.println(date); // Tue Dec 11 00:00:00 CST 2018
    }
}

2.3 practice

Please use the date and time related API to calculate how many days a person has been born.

Idea:

1. Obtain the millisecond value corresponding to the current time

2. Get the MS value corresponding to your birth date

3. Subtract two times (current time – date of birth)

Code implementation:

public static void function() throws Exception {
	System.out.println("Please enter birth date format YYYY-MM-dd");
	// Get the date of birth and enter it with the keyboard
	String birthdayString = new Scanner(System.in).next();
	// Convert a Date string to a Date object
	// Create a SimpleDateFormat object to write the date pattern
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	// Call the parse method to convert the string into a date object
	Date birthdayDate = sdf.parse(birthdayString);	
	// Get today's Date object
	Date todayDate = new Date();	
	// Convert the two dates into millisecond values, and the method getTime of the Date class
	long birthdaySecond = birthdayDate.getTime();
	long todaySecond = todayDate.getTime();
	long secone = todaySecond-birthdaySecond;	
	if (secone < 0){
		System.out.println("Not yet born");
	} else {
		System.out.println(secone/1000/60/60/24);
	}
}

2.4 Calendar

concept

We've all seen the calendar

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-kBlAcmsK-1624549048202)(img \ calendar. jpg)]

java.util.Calendar is a calendar class. It appears after Date and replaces many methods of Date. This class encapsulates all possible time information into static member variables for easy access. Calendar class is convenient to obtain various time attributes.

Acquisition method

Calendar is an abstract class. Due to language sensitivity, the calendar class is not created directly when creating objects, but through static methods. It returns subclass objects as follows:

Calendar static method

  • public static Calendar getInstance(): get a calendar using the default time zone and locale

For example:

import java.util.Calendar;

public class Demo06CalendarInit {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
    }    
}

common method

According to the API document of Calendar class, the common methods are:

  • public int get(int field): returns the value of the given calendar field.
  • public void set(int field, int value): set the given calendar field to the given value.
  • public abstract void add(int field, int amount): adds or subtracts the specified amount of time for a given calendar field according to the rules of the calendar.
  • public Date getTime(): returns a Date object representing this Calendar time value (millisecond offset from epoch to present).

Many member constants are provided in the Calendar class to represent a given Calendar field:

field valuemeaning
YEARyear
MONTHMonth (starting from 0, can be used with + 1)
DAY_OF_MONTHDay (day) of the month
HOURHour (12 hour system)
HOUR_OF_DAYHour (24-hour system)
MINUTEbranch
SECONDsecond
DAY_OF_WEEKDay of the week (day of the week, Sunday is 1, can be - 1)

get/set method

The get method is used to obtain the value of the specified field, and the set method is used to set the value of the specified field. The code usage demonstration:

import java.util.Calendar;

public class CalendarUtil {
    public static void main(String[] args) {
        // Create Calendar object
        Calendar cal = Calendar.getInstance();
        // Set year 
        int year = cal.get(Calendar.YEAR);
        // Set month
        int month = cal.get(Calendar.MONTH) + 1;
        // Set day
        int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
        System.out.print(year + "year" + month + "month" + dayOfMonth + "day");
    }    
}
import java.util.Calendar;

public class Demo07CalendarMethod {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, 2020);
        System.out.print(year + "year" + month + "month" + dayOfMonth + "day"); // January 17, 2020
    }
}

add method

The add method can add or subtract the value of the specified calendar field. If the second parameter is a positive number, add the offset; if it is a negative number, subtract the offset. Code such as:

import java.util.Calendar;

public class Demo08CalendarMethod {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        System.out.print(year + "year" + month + "month" + dayOfMonth + "day"); // January 17, 2018
        // Using the add method
        cal.add(Calendar.DAY_OF_MONTH, 2); // Plus 2 days
        cal.add(Calendar.YEAR, -3); // Minus 3 years
        System.out.print(year + "year" + month + "month" + dayOfMonth + "day"); // January 18, 2015; 
    }
}

getTime method

The getTime method in Calendar does not get the millisecond time, but the corresponding Date object.

import java.util.Calendar;
import java.util.Date;

public class Demo09CalendarMethod {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        Date date = cal.getTime();
        System.out.println(date); // Tue Jan 16 16:03:09 CST 2018
    }
}

Tips:

The Western week starts on Sunday and China on Monday.

In the Calendar class, the month is represented by 0-11 for January to December.

The date has a size relationship. The later the time, the greater the time.

Chapter III System class

java.lang.System class provides a large number of static methods to obtain System related information or System level operations. In the API document of System class, the common methods are:

  • public static long currentTimeMillis(): returns the current time in milliseconds.
  • Public static void array copy (object SRC, int srcpos, object DeST, int destpos, int length): copies the data specified in the array to another array.

3.1 currentTimeMillis method

In fact, the currentTimeMillis method is to obtain the millisecond difference between the current system time and 00:00 on January 1, 1970

import java.util.Date;

public class SystemDemo {
    public static void main(String[] args) {
       	//Gets the current time in milliseconds
        System.out.println(System.currentTimeMillis()); // 1516090531144
    }
}

practice

The time (in milliseconds) it takes to verify that the for loop prints numbers 1-9999

public class SystemTest1 {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            System.out.println(i);
        }
        long end = System.currentTimeMillis();
        System.out.println("Total time taken MS:" + (end - start));
    }
}

3.2 arraycopy method

  • Public static void array copy (object SRC, int srcpos, object DeST, int destpos, int length): copies the data specified in the array to another array.

The copy action of array is system level and has high performance. System. The arraycopy method has five parameters, which mean:

Parameter serial numberParameter nameParameter typeParameter meaning
1srcObjectSource array
2srcPosintSource array index start position
3destObjecttarget array
4destPosintTarget array index start position
5lengthintNumber of copied elements

practice

Copy the first three elements of src array to the first three positions of dest array. Before copying elements: src array elements [1,2,3,4,5], dest array elements [6,7,8,9,10]. After copying elements: src array elements [1,2,3,4,5], dest array elements [1,2,3,9,10]

import java.util.Arrays;

public class Demo11SystemArrayCopy {
    public static void main(String[] args) {
        int[] src = new int[]{1,2,3,4,5};
        int[] dest = new int[]{6,7,8,9,10};
        System.arraycopy( src, 0, dest, 0, 3);
        /*After the code runs: the elements in the two arrays have changed
         src Array elements [1,2,3,4,5]
         dest Array elements [1,2,3,9,10]
        */
    }
}

Chapter 4 StringBuilder class

4.1 string splicing

Since the object content of the String class cannot be changed, a new object will always be created in memory whenever String splicing is performed. For example:

public class StringDemo {
    public static void main(String[] args) {
        String s = "Hello";
        s += "World";
        System.out.println(s);
    }
}

In the API, the String class is described as follows: strings are constants, and their values cannot be changed after creation.

According to this sentence, our code actually produces three strings, namely "hello", "World" and "HelloWorld". The reference variable s first points to the Hello object, and finally points to the spliced new string object, namely HelloWord.

[the transfer of external chain pictures fails. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-iy84xITX-1624549048203)(img\String splicing problem. bmp)]

It can be seen that if you splice strings, a new String object will be constructed each time, which is time-consuming and a waste of space. To solve this problem, you can use Java Lang.stringbuilder class.

4.2 StringBuilder overview

Check Java Lang. StringBuilder API. StringBuilder is also called variable character sequence. It is a String buffer similar to String. The length and content of the sequence can be changed through some method calls.

Originally, StringBuilder is a string buffer, that is, it is a container that can hold many strings. And can perform various operations on the string.

It has an array inside to store the string content. When string splicing, new content is directly added to the array. StringBuilder will automatically maintain the expansion of the array. The principle is shown in the following figure: (16 character space by default, exceeding automatic expansion)

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-fwj0yjlk-1624549048204) (IMG \ 06 StringBuilder principle. png)]

4.3 construction method

According to the API document of StringBuilder, there are two common construction methods:

  • public StringBuilder(): construct an empty StringBuilder container.
  • public StringBuilder(String str): construct a StringBuilder container and add strings.
public class StringBuilderDemo {
    public static void main(String[] args) {
        StringBuilder sb1 = new StringBuilder();
        System.out.println(sb1); // (blank)
        // Using parametric construction
        StringBuilder sb2 = new StringBuilder("itcast");
        System.out.println(sb2); // itcast
    }
}

4.4 common methods

There are two methods commonly used by StringBuilder:

  • public StringBuilder append(...): Adds the string form of any type of data and returns the current object itself.
  • public String toString(): converts the current StringBuilder object to a String object.

append method

The append method has multiple overloaded forms and can receive any type of parameter. Any data as a parameter will add the corresponding string content to StringBuilder. For example:

public class Demo02StringBuilder {
	public static void main(String[] args) {
		//create object
		StringBuilder builder = new StringBuilder();
		//Public StringBuilder append (any type)
		StringBuilder builder2 = builder.append("hello");
		//Compare it
		System.out.println("builder:"+builder);
		System.out.println("builder2:"+builder2);
		System.out.println(builder == builder2); //true
	    // Any type can be added
		builder.append("hello");
		builder.append("world");
		builder.append(true);
		builder.append(100);
		// In our development, we will encounter the situation of returning an object after calling a method. Then continue calling the method with the returned object.
        // At this time, we can put the code together now, like the append method. The code is as follows
		//Chain programming
		builder.append("hello").append("world").append(true).append(100);
		System.out.println("builder:"+builder);
	}
}

Note: StringBuilder has overridden the toString method in Object.

toString method

Through the toString method, the StringBuilder object will be converted to an immutable String object. For example:

public class Demo16StringBuilder {
    public static void main(String[] args) {
        // Chain creation
        StringBuilder sb = new StringBuilder("Hello").append("World").append("Java");
        // Call method
        String str = sb.toString();
        System.out.println(str); // HelloWorldJava
    }
}

Chapter V packaging

5.1 general

Java provides two type systems, basic type and reference type. Using basic types is efficient. However, in many cases, objects will be created for use, because objects can do more functions. If you want our basic types to operate like objects, you can use the wrapper classes corresponding to the basic types, as follows:

Basic typeCorresponding wrapper class (in java.lang package)
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

5.2 packing and unpacking

The process of back and forth conversion between the basic type and the corresponding packing class object is called "packing" and "unpacking":

  • Boxing: convert from basic type to corresponding wrapper class object.

  • Unpacking: convert from packing class object to corresponding basic type.

Take Integer and int as an example: (just understand the code)

Basic value - > packing object

Integer i = new Integer(4);//Using constructor functions
Integer iii = Integer.valueOf(4);//Use the valueOf method in the wrapper class

Packing object ----- > basic value

int num = i.intValue();

5.3 automatic packing and unpacking

Since we often need to convert between basic types and packaging classes, the boxing and unpacking of basic types and packaging classes can be completed automatically from Java 5 (JDK 1.5). For example:

Integer i = 4;//Automatic packing. Equivalent to integer I = integer valueOf(4);
i = i + 5;//Right of the equal sign: convert the I object to the basic value (automatic unpacking) i.intValue() + 5;
//After the addition operation is completed, box again and convert the basic value into an object.

5.3 conversion between basic type and string

Convert basic type to String

There are three ways to convert a basic type to a String. You can see from the materials after class that only the simplest way is discussed here:

The basic type can be directly connected with ""; For example: 34+""

String is converted to the corresponding basic type

Except for the Character class, all other wrapper classes have parseXxx static methods, which can convert string parameters to corresponding basic types:

  • public static byte parseByte(String s): converts a string parameter to the corresponding byte basic type.
  • public static short parseShort(String s): converts a string parameter to the corresponding short basic type.
  • public static int parseInt(String s): converts a string parameter to the corresponding int basic type.
  • public static long parseLong(String s): converts a string parameter to the corresponding long basic type.
  • public static float parseFloat(String s): converts a string parameter to the corresponding float basic type.
  • public static double parseDouble(String s): converts a string parameter to the corresponding double basic type.
  • public static boolean parseBoolean(String s): converts a string parameter to the corresponding boolean basic type.

Code usage (only take the static method parseXxx of Integer class as an example), such as:

public class Demo18WrapperParse {
    public static void main(String[] args) {
        int num = Integer.parseInt("100");
    }
}

Note: if the content of the string parameter cannot be correctly converted to the corresponding basic type, Java. Java. XML will be thrown Lang.numberformatexception exception.

Keywords: Java

Added by klaibert26 on Tue, 25 Jan 2022 12:39:08 +0200