Java基础进阶笔记 - Day01 - 第三章 System类
Java基础进阶笔记 - Day01 - 第三章 System类
系统:Win10
JDK:1.8.0_121
IDE:IntelliJ IDEA 2017.3.7
java.long.System 类中提供了大量的静态方法,可以获取与系统相关的信息或系统级操作,在System类的API文档中,常用的方法有:
- public static long currentTimeMillis():返回以毫秒为单位的当前时间
- public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length):将数组中指定的数据拷贝到另一个数组中
3.1 currentTimeMills方法
实际上,currentTimeMills方法就是获取当前系统时间与1970年01月01日00:00:00之间的毫秒差值
public class SystemDemo01 {
public static void main(String[] args) {
// 获取当前时间毫秒值
System.out.println(System.currentTimeMillis()); // 1606377341807
}
}
运行结果如下:
练习
输出for循环打印数字1-9999所需使用的时间(毫秒)
public class SystemDemo02 {
public static void main(String[] args) {
// 获取当前时间毫秒值
long startTime = System.currentTimeMillis();
for (int i = 1; i <= 9999; i++) {
System.out.println(i);
}
long endTime = System.currentTimeMillis();
System.out.println("共耗时 " + (endTime - startTime) + "毫秒!");
}
}
运行结果:
3.2 arraycopy方法
arraycopy的数组拷贝动作是系统级的,性能很高。System.arraycopy方法具有5个参数,含义分别为:
参数序列 | 参数名称 | 参数类型 | 参数含义 |
---|---|---|---|
1 | src | Object | 源数组 |
2 | srcPos | int | 源数组索引起始位置 |
3 | dest | Object | 目标数组 |
4 | destPos | int | 目标数组索引起始位置 |
5 | length | length | 复制元素个数 |
练习
将src数组中前3个元素,复制到dest数组的第2个位置到第4个位置上。src数组元素[1,2,3,4,5],dest数组元素[6,7,8,9,10]。复制后:src数组元素[1,2,3,4,5],dest数组元素[6,1,2,3,10]
public class SystemDemo03 {
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.out.println("复制前:src数组" + Arrays.toString(src) + ",dest数组" + Arrays.toString(dest));
System.arraycopy(src,0,dest,1,3);
System.out.println("复制后:src数组" + Arrays.toString(src) + ",dest数组" + Arrays.toString(dest));
}
}
运行结果: