Java數組講解和Arrays工具類

1、數組重點概念
數組的長度是確定的,大小不可變。其元素是相同類型,不允許出現混合類型。

2、數組定義

//兩種中括號位置都可,推薦中括號寫在類型後
int[] a = null;//數組聲明,使用前需要給數組定義大小
a = new int[3];//大小定義
String str[] = new String[3];
int[] arrs = {1,2,3};

3、數組打印

//3.1簡單的for循環打印
int[] arrs = {1,2,3};
for (int i = 0; i < arrs.length; i++) {
	System.out.println(arrs[i]);
}

//3.2foreach(用於讀取數組或集合中所有的元素,即對數組進行遍歷。)
for (int x : arrs) {//注意這裏的x不是下標
	System.out.println(x);
}

//3.3Arrays
import java.util.Arrays;
Arrays.toString(arrs)

4、數組拷貝(可以通過這個方法實現數組中元素的刪除插入效果)

//System.arraycopy(src{原數組}, srcPos{原數組從哪個索引開始拷貝}, dest{新數組}, destPos{新數組從哪個索引開始存儲}, length{原數組需要被拷貝長度});
String[] arrs1 = {"a0","b1","c2","d3","e4"};
String[] arrs2 = new String[5];
System.arraycopy(arrs1, 1, arrs2, 2, 2);
//實現刪除效果(index索引)System.arraycopy(arrs1,index+1,arrs1,index,arrs1.length-index-1);arrs1[arrs1.length-1] = null;
for (String string : arrs2) {
	System.out.println(string);//==>打印內容null null b1 c2 null
}

5、Arrays工具類

import java.util.Arrays;
int[] arrs = {1,2,3,9,4};
//打印
Arrays.toString(arrs);
//排序
Arrays.sort(arrs);
//二分法查找元素(找到會返回索引位置,找不到返回-1)
Arrays.binarySearch(arrs, 3);

6、多維數組

//二維數組定義
int[][] arrs = new int[3][];//第一個括號內大小必須指定,存儲的是包含的一維數組的地址。
arrs[0] = new int[]{1};
arrs[1] = new int[]{1,2};
arrs[2] = new int[]{1,2,3,4};
//打印二維數組
for (int[] arr : arrs) {
	System.out.println(Arrays.toString(arr));
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章