System,Math

System类

java.lang.System类中提供了大量的静态方法,可以获取与系统相关的信息或系统级操作,在System类的API文档中,常用的方法有:

**public static long currentTimeMillis()**:返回以毫秒为单位的当前时间。

**public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)**:将数组中指定的数据拷贝到另一个数组中。

currentTimeMillis方法

实际上,currentTimeMillis方法就是获取当前系统时间与1970年01月01日00:00点之间的毫秒差值

1
2
3
4
5
6
7
import java.util.Date;
public class SystemDemo {
public static void main(String[] args) {
//获取当前时间毫秒值
System.out.println(System.currentTimeMillis()); // 1516090531144
}
}

练习

验证for循环打印数字1-9999所需要使用的时间(毫秒)

1
2
3
4
5
6
7
8
9
10
11
private static void demo01() {
//程序执行前,获取一次毫秒值
long s = System.currentTimeMillis();
//执行for循环
for (int i = 1; i <=9999 ; i++) {
System.out.println(i);
}
//程序执行后,获取一次毫秒值
long e = System.currentTimeMillis();
System.out.println("程序共耗时:"+(e-s)+"毫秒");//程序共耗时:106毫秒
}

arraycopy方法

public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length):

将数组中指定的数据拷贝到另一个数组中。

数组的拷贝动作是系统级的,性能很高。System.arraycopy方法具有5个参数,含义分别为:

  • src - 源数组。
  • srcPos - 源数组中的起始位置(起始索引)。
  • dest - 目标数组。
  • destPos - 目标数据中的起始位置。
  • length - 要复制的数组元素的数量。

练习:

将src数组中前3个元素,复制到dest数组的前3个位置上

复制元素前:

src数组元素[1,2,3,4,5],dest数组元素[6,7,8,9,10]

复制元素后:

src数组元素[1,2,3,4,5],dest数组元素[1,2,3,9,10]

1
2
3
4
5
6
7
8
//定义源数组
int[] src = {1,2,3,4,5};
//定义目标数组
int[] dest = {6,7,8,9,10};
System.out.println("复制前:"+ Arrays.toString(dest)); //[6, 7, 8, 9, 10]
//使用System类中的arraycopy把源数组的前3个元素复制到目标数组的前3个位置上
System.arraycopy(src,0,dest,0,3);
System.out.println("复制后:"+ Arrays.toString(dest)); //[1, 2, 3, 9, 10]

Math类

java.util.Math类是数学相关的工具类,里面提供了大量的静态方法,完成与数学运算相关的操作。

**public static double abs(double num)**:获取绝对值。有多种重载。

**public static double ceil(double num)**:向上取整。

**public static double floor(double num)**:向下取整。

public static long **round(double num)**:四舍五入。

public static int max(int a,int b) 返回两个 int 值中较大的一个。

public static int min(int a,int b) 返回两个 int 值中较小的一个。

Math.PI代表近似的圆周率常量(double)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
   // 获取绝对值
System.out.println(Math.abs(-2.5)); // 2.5

// 向上取整
System.out.println(Math.ceil(3.9)); // 4.0
System.out.println(Math.ceil(3.1)); // 4.0

// 向下取整,抹零
System.out.println(Math.floor(30.9)); // 30.0
System.out.println(Math.floor(31.0)); // 31.0

//四舍五入
System.out.println(Math.round(20.4)); // 20
System.out.println(Math.round(10.5)); // 11

//如果刚好在两个整数的中间,则选择更接近正无穷的那个整数
System.out.println(Math.round(-10.5)); //-10
System.out.println(Math.round(-10.6));


System,Math
http://example.com/2023/05/13/Java/Java常用类/System,Math/
作者
PALE13
发布于
2023年5月13日
许可协议