Java基礎 第三節 第三課
System 類
概述
currentTimeMillis 方法
練習
arraycopy 方法
練習
概述
java.lang.System類中提供了大量的靜態方法, 可以獲取與系統相關的信息或系統級操作. 在 System 類的 API 文檔中, 常用的方法有:
public static long currentTimeMills(): 返回以毫秒為單位的當前時間
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length): 將數組中指定的數據拷貝到另一個數組中
currentTimeMillis 方法
實際上, currentTImeMillis 方法就是獲取當前系統時間與 1970 年 01 月 01 日 00:00 點之間的毫秒差值.
public class Test14 { public static void main(String[] args) { // 獲取當前時間毫秒值 System.out.println(System.currentTimeMillis()); // 輸出結果: 1606453054627 } }
1
2
3
4
5
6
練習
驗證 for 循環打印數字 1-9999 所需要使用的時間. (毫秒)
public class Test15 { 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) + " 毫秒"); } } 輸出結果: 總共耗時: 602 毫秒
1
2
3
4
5
6
7
8
9
10
11
12
13
arraycopy 方法
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length): 將數組中指定的數據拷貝到另一個數組中.
數組的拷貝動作是系統級的, 性能很高. System.arraycopy 方法具體有 5 個參數, 含義分別為:
練習
將 src 數組中前 3 個元素, 復制到 dest 數組的前 3 個位置上復制元素前: scr 數組元素 [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; public class Test16 { public static void main(String[] args) { // 定義src, dest數組 int[] src = {1,2,3,4,5}; int[] dest = {6,7,8,9,10}; System.out.println("復制元素前"); System.out.println(Arrays.toString(src)); System.out.println(Arrays.toString(dest)); // 調用arraycopy方法 System.arraycopy(src,0,dest,0,3); System.out.println("復制元素后"); System.out.println(Arrays.toString(src)); System.out.println(Arrays.toString(dest)); } } 輸出結果: 復制元素前 [1, 2, 3, 4, 5] [6, 7, 8, 9, 10] 復制元素后 [1, 2, 3, 4, 5] [1, 2, 3, 9, 10]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Java 數據結構
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。