Detailed Explanation of the System Class of Java's API Detailed Explanation

2 System class

2.1 Overview

tips: understand the content

Looking at the API documentation, we can see that the definition of the System class in the API documentation is as follows:

 

The package of the System class is the java.lang package, so there is no need to import the package when using it. And the System class is final modified, so this class cannot be inherited.

System contains some common methods of system operation. For example, to obtain the millisecond value corresponding to the current time, or to terminate the current JVM and so on.

To use the System class, we need to create an object of this class first, then creating an object requires the help of a constructor. Therefore, we need to check the API documentation first to see if there is a corresponding construction method for the System class in the API documentation. Through the API documentation to

Take a look at the members of the System class, as follows:

 

The available construction methods are not reflected in the API documentation, so we cannot directly create objects of the System class through the new keyword. At the same time, we found that the methods in the System class are all static, so we can call them directly through the class name (Nested

Class Summary internal class or internal interface description).

2.2 Common methods

tips: focus on explaining the content

Introduction to common methods

The common methods in the System class that we are going to learn are as follows:

public static long currentTimeMillis()			// 获取当前时间所对应的毫秒值(当前时间为0时区所对应的时间即就是英国格林尼治天文台旧址所在位置)
public static void exit(int status)				// 终止当前正在运行的Java虚拟机,0表示正常退出,非零表示异常退出
public static native void arraycopy(Object src,  int  srcPos, Object dest, int destPos, int length); // 进行数值元素copy

Case presentation

Next, we will demonstrate the characteristics of these methods through some cases.

Case 1 : Demo currentTimeMillis method

public class SystemDemo01 {

    public static void main(String[] args) {

        // 获取当前时间所对应的毫秒值
        long millis = System.currentTimeMillis();

        // 输出结果
        System.out.println("当前时间所对应的毫秒值为:" + millis);

    }

}

Run the program to test, the console output is as follows:

当前时间所对应的毫秒值为:1576050298343

The significance of obtaining the millisecond value of the current time: We often need to count the execution time of a certain piece of code. At this point, we can get the time once before executing this code, get the system time again after the execution is complete, and then calculate the difference between the two times,

This difference is the time required after this code is executed. As shown in the following code:

public class SystemDemo2 {
    public static void main(String[] args) {
        //判断1~100000之间有多少个质数

        long start = System.currentTimeMillis();

        for (int i = 1; i <= 100000; i++) {
            boolean flag = isPrime2(i);
            if (flag) {
                System.out.println(i);
            }
        }
        long end = System.currentTimeMillis();
        //获取程序运行的总时间
        System.out.println(end - start); //方式一:1514 毫秒  方式二:71毫秒
    }

    //以前判断是否为质数的方式
    public static boolean isPrime1(int number) {
        for (int i = 2; i < number; i++) {
            if (number % i == 0) {
                return false;
            }
        }
        return true;
    }

    //改进之后判断是否为质数的方式(效率高)
    public static boolean isPrime2(int number) {
        for (int i = 2; i <= Math.sqrt(number); i++) {
            if (number % i == 0) {
                return false;
            }
        }
        return true;
    }
}

Case 2 : Demonstrate the exit method

public class SystemDemo01 {

    public static void main(String[] args) {
        
        // 输出
        System.out.println("程序开始执行了.....");
        
        // 终止JVM
        System.exit(0);
        
        // 输出
        System.out.println("程序终止了..........");
        
    }
    
}

Run the program to test, the console output is as follows:

程序开始执行了.....

At this point, you can see that only "the program has started..." is output on the console. Since the JVM is terminated, the output "the program has terminated..." is not executed.

Case 3 : Demo of the arraycopy method

Method parameter description:

// src: 	 源数组
// srcPos:  源数值的开始位置
// dest:    目标数组
// destPos: 目标数组开始位置
// length:   要复制的元素个数
public static native void arraycopy(Object src,  int  srcPos, Object dest, int destPos, int length); 

The code looks like this:

public class SystemDemo01 {

    public static void main(String[] args) {

        // 定义源数组
        int[] srcArray = {23 , 45 , 67 , 89 , 14 , 56 } ;

        // 定义目标数组
        int[] desArray = new int[10] ;

        // 进行数组元素的copy: 把srcArray数组中从0索引开始的3个元素,从desArray数组中的1索引开始复制过去
        System.arraycopy(srcArray , 0 , desArray , 1 , 3);

        // 遍历目标数组
        for(int x = 0 ; x < desArray.length ; x++) {
            if(x != desArray.length - 1) {
                System.out.print(desArray[x] + ", ");
            }else {
                System.out.println(desArray[x]);
            }

        }

    }

}

Run the program to test, the console output is as follows:

0, 23, 45, 67, 0, 0, 0, 0, 0, 0

We can see from the console output that the array elements are indeed copied.

Using this method we can also complete the deletion of array elements, as follows:

public class SystemDemo02 {
    public static void main(String[] args) {
        // 定义一个数组
        int[] srcArray = {23 , 45 , 67 , 89 , 14 , 56 } ;
        // 删除数组中第3个元素(67):要删除67这个元素,我们只需要将67后面的其他元素依次向前进行移动即可
        System.arraycopy(srcArray , 3 , srcArray , 2 , 3);
        // 遍历srcArray数组
        for(int x = 0 ; x < srcArray.length ; x++) {
            if(x != desArray.length - 1) {
                System.out.print(srcArray[x] + ", ");
            }else {
                System.out.println(srcArray[x]);
            }
        }
    }

Run the program to test, the console output is as follows:

23, 45, 89, 14, 56, 56 

Through the console output results, we can see that there is an extra 56 elements at this time. At this time, we only need to set the last position to 0. As follows:

public class SystemDemo02 {
    public static void main(String[] args) {
        // 定义一个数组
        int[] srcArray = {23 , 45 , 67 , 89 , 14 , 56 } ;
        // 删除数组中第3个元素(67):要删除67这个元素,我们只需要将67后面的其他元素依次向前进行移动即可
        System.arraycopy(srcArray , 3 , srcArray , 2 , 3);
        // 将最后一个位置的元素设置为0
        srcArray[srcArray.length - 1] = 0 ;
        // 遍历srcArray数组
        for(int x = 0 ; x < srcArray.length ; x++) {
            if(x != srcArray.length - 1 ) {
                System.out.print(srcArray[x] + ", ");
            }else {
                System.out.println(srcArray[x]);
            }
        }
    }
}

Run the program to test, the console output is as follows:

23, 45, 89, 14, 56, 0

At this point we can see that the element "67" has been deleted. The other elements behind 67 are moved forward one by one.

The underlying details of the arraycopy method:

1. If the data source array and destination array are both basic data types, the types of the two must be consistent, otherwise an error will be reported

2. When copying, you need to consider the length of the array. If it exceeds the range, an error will be reported

3. If the data source array and destination array are both reference data types, then the subclass type can be assigned to the parent class type

Code example:

public class SystemDemo3 {
    public static void main(String[] args) {
        //public static void arraycopy(数据源数组,起始索引,目的地数组,起始索引,拷贝个数) 数组拷贝
        //细节:
        //1.如果数据源数组和目的地数组都是基本数据类型,那么两者的类型必须保持一致,否则会报错
        //2.在拷贝的时候需要考虑数组的长度,如果超出范围也会报错
        //3.如果数据源数组和目的地数组都是引用数据类型,那么子类类型可以赋值给父类类型

        Student s1 = new Student("zhangsan", 23);
        Student s2 = new Student("lisi", 24);
        Student s3 = new Student("wangwu", 25);

        Student[] arr1 = {s1, s2, s3};
        Person[] arr2 = new Person[3];
        //把arr1中对象的地址值赋值给arr2中
        System.arraycopy(arr1, 0, arr2, 0, 3);

        //遍历数组arr2
        for (int i = 0; i < arr2.length; i++) {
            Student stu = (Student) arr2[i];
            System.out.println(stu.getName() + "," + stu.getAge());
        }
    }
}

class Person {
    private String name;
    private int age;

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    /**
     * 获取
     *
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * 设置
     *
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取
     *
     * @return age
     */
    public int getAge() {
        return age;
    }

    /**
     * 设置
     *
     * @param age
     */
    public void setAge(int age) {
        this.age = age;
    }

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


class Student extends Person {

    public Student() {
    }

    public Student(String name, int age) {
        super(name, age);
    }
}

Guess you like

Origin blog.csdn.net/qq_69748833/article/details/132516908