Common API_ two

primary coverage

Learning objectives

-[] be able to describe the characteristics of the object class - [] be able to override the toString method of the object class - [] be able to override the equals method of the object class - [] be able to use the date class to output the current date - [] be able to use the method of formatting the date into a string - [] be able to use the method of converting a string into a date - [] be able to use the array copy method of the system class - [] Be able to use the system class to obtain the current millisecond time value - [] be able to say the problems that can be solved by using the StringBuilder class - [] be able to use the StringBuilder for string splicing - [] be able to say the packaging class names corresponding to 8 basic types - [] be able to say automatic packing The concept of automatic unpacking - [] can convert a string to a corresponding basic type - [] can convert a basic type to a corresponding string

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 document of the object class, the object class contains 11 methods. Today we mainly learn two of them:

1.2 toString method

Method summary

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 custom person class:

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

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

    // 省略构造器与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:

1.3 equals method

Method summary

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 (this == o)
            return true;
        // 如果参数为空,或者类型信息不一样,则认为不同
        if (o == null || getClass() != o.getClass())
            return false;
        // 转换为当前类型
        Person person = (Person) o;
        // 要求基本类型相等,并且将引用类型交给java.util.Objects类的equals静态方法取用结果
        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() for automatic code generation. As shown in the figure below:

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:

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.

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

import java.util.Date;

public class Demo01Date {
    public static void main(String[] args) {
        // 创建日期对象,把当前的时间
        System.out.println(new Date()); // Fri Jan 31 15:53:22 GMT+08:00 2020
        // 创建日期对象,把当前的毫秒值转成日期对象
        System.out.println(new Date(0L)); // Thu Jan 01 08:00:00 GMT+08:00 1970
    }
}

common method

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

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.

Construction method

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

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

Format Rules

Common format rules are:

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) {
        // 对应的日期格式如:2020-01-31 15:06:38
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }    
}

common method

Common methods of dateformat class are:

Format method

The code using the format method is:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
 把Date对象转换成String
*/
public class Demo03DateFormatMethod {
    public static void main(String[] args) {
        Date date = new Date();
        // 创建日期格式化对象,在获取格式化对象时可以指定风格
        DateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
        String str = df.format(date);
        System.out.println(str); // 2020年01月31日
    }
}

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;
/*
 把String转换成Date对象
*/
public class Demo04DateFormatMethod {
    public static void main(String[] args) throws ParseException {
        DateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
        String str = "2018年12月11日";
        Date date = df.parse(str);
        System.out.println(date); // Fri Jan 31 00:00:00 GMT+08:00 2020
    }
}

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("请输入出生日期 格式 YYYY-MM-dd");
	// 获取出生日期,键盘输入
	String birthdayString = new Scanner(system.in).next();
	// 将字符串日期,转成Date对象
	// 创建SimpleDateFormat对象,写日期模式
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	// 调用方法parse,字符串转成日期对象
	Date birthdayDate = sdf.parse(birthdayString);	
	// 获取今天的日期对象
	Date todayDate = new Date();	
	// 将两个日期转成毫秒值,Date类的方法getTime
	long birthdaySecond = birthdayDate.getTime();
	long todaySecond = todayDate.getTime();
	long secone = todaySecond-birthdaySecond;	
	if (secone < 0){
		System.out.println("还没出生呢");
	} else {
		System.out.println(secone/1000/60/60/24);
	}
}

2.4 calendar

concept

We've all seen the calendar

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

For example:

import java.util.Calendar;

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

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

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

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:

Get method:

import java.util.Calendar;

public class CalendarUtil {
    public static void main(String[] args) {
        // 创建Calendar对象
        Calendar cal = Calendar.getInstance();
        // 设置年 
        int year = cal.get(Calendar.YEAR);
        // 设置月
        int month = cal.get(Calendar.MONTH) + 1;
        // 设置日
        int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
        System.out.print(year + "年" + month + "月" + dayOfMonth + "日"); // 2020年1月31日
    }    
}

Set method:

import java.util.Calendar;

public class Demo07CalendarMethod {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR,2020);
		cal.set(Calendar.MONTH,1);
		cal.set(Calendar.DAY_OF_MONTH,31);
		// 上面三局等同于cal.set(2020,1,31);
		
		int year = cal.get(Calendar.YEAR);
        // 设置月
        int month = cal.get(Calendar.MONTH) + 1;
        // 设置日
        int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);

        System.out.print(year + "年" + month + "月" + dayOfMonth + "日"); // 2020年1月31日
    }
}

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();
		int year = cal.get(Calendar.YEAR);
        // 设置月
        int month = cal.get(Calendar.MONTH) + 1;
        // 设置日
        int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
        System.out.print(year + "年" + month + "月" + dayOfMonth + "日"); // 2020年1月31日
        // 使用add方法
        cal.add(Calendar.DAY_OF_MONTH,2); // 加2天
        cal.add(Calendar.YEAR,-3); // 减3年
		year = cal.get(Calendar.YEAR);
        // 设置月
        month = cal.get(Calendar.MONTH) + 1;
        // 设置日
        dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
        System.out.print(year + "年" + month + "月" + dayOfMonth + "日"); // 2017年2月2日
    }
}

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); // Fri Jan 31 23:18:15 GMT+08:00 2020
    }
}

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:

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) {
       	//获取当前时间毫秒值
        System.out.println(System.currentTimeMillis()); // 1580485508707
    }
}

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("共耗时毫秒:" + (end - start));
    }
}

3.2 arraycopy method

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

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,5], DeST array elements [1,10]

import java.util.Arrays;

public class Demo11SystemArrayCopy {
    public static void main(String[] args) {
        int[] src = new int[]{1,5};
        int[] dest = new int[]{6,10};
        System.arraycopy( src,dest,3);
        /*代码运行后:两个数组中的元素发生了变化
         src数组元素[1,5]
         dest数组元素[1,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.

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)

4.3 construction method

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

public class StringBuilderDemo {
    public static void main(String[] args) {
        StringBuilder sb1 = new StringBuilder();
        System.out.println(sb1); // (空白)
        // 使用带参构造
        StringBuilder sb2 = new StringBuilder("helloworld");
        System.out.println(sb2); // helloworld
    }
}

4.4 common methods

There are two methods commonly used by StringBuilder:

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) {
		//创建对象
		StringBuilder builder = new StringBuilder();
		//public StringBuilder append(任意类型)
		StringBuilder builder2 = builder.append("hello");
		//对比一下
		System.out.println("builder:"+builder);
		System.out.println("builder2:"+builder2);
		System.out.println(builder == builder2); //true
	    // 可以添加 任何类型
		builder.append("hello");
		builder.append("world");
		builder.append(true);
		builder.append(100);
		// 在我们开发中,会遇到调用一个方法后,返回一个对象的情况。然后使用返回的对象继续调用方法。
        // 这种时候,我们就可以把代码现在一起,如append方法一样,代码如下
		//链式编程
		builder.append("hello").append("world").append(true).append(100);
		System.out.println("builder:"+builder);
	}
}

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) {
        // 链式创建
        StringBuilder sb = new StringBuilder("Hello").append("World").append("Java");
        // 调用方法
        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:

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":

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

Basic value - > packing object

Integer i = new Integer(4);//使用构造函数函数
Integer iii = Integer.valueOf(4);//使用包装类中的valueOf方法

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, starting from Java 5 (JDK 1.5), the boxing and unpacking of basic types and packaging classes can be completed automatically. For example:

Integer i = 4;//自动装箱。相当于Integer i = Integer.valueOf(4);
i = i + 5;//等号右边:将i对象转成基本数值(自动拆箱) i.intValue() + 5;
//加法运算完成后,再次装箱,把基本数值转成对象。

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:

基本类型直接与””相连接即可;如:34+""

String is converted to the corresponding basic type

Except for the character class, all other wrapper classes have parsexxx static methods that can convert string parameters to corresponding basic types:

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");
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>