- 能够使用System类的数组复制方法
- 能够使用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方法
- 返回以毫秒为单位的当前时间
public static long currentTimeMillis()
实际上,currentTimeMillis
方法就是 获取当前系统时间与1970年01月01日00:00点之间的毫秒差值
import java.util.Date;
public class SystemDemo {
public static void main(String[] args) {
//获取当前时间毫秒值
System.out.println(System.currentTimeMillis()); // 1516090531144
}
}
案例:打印运行所需时间
练习验证for循环打印数字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));
}
}
arraycopy方法
- 将数组中指定的数据拷贝到另一个数组中。
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);
参数
- 数组的拷贝动作是系统级的,性能很高。
System.arraycopy
方法具有5个参数
含义分别为:
参数序号 | 参数名称 | 参数类型 | 参数含义 |
---|---|---|---|
1 | src | Object | 源数组 |
2 | srcPos | int | 源数组索引起始位置(起始索引) |
3 | dest | Object | 目标数组 |
4 | destPos | int | 目标数组索引起始位置 |
5 | length | int | 要复制的数组元素的数量 |
案例:数组的拷贝
将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]
代码:
import java.util.Arrays;
/*
练习:
将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]
*/
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);
System.out.println(Arrays.toString(src));
System.out.println(Arrays.toString(dest));
}
}
结果:
[1, 2, 3, 4, 5]
[1, 2, 3, 9, 10]