糯米文學吧

位置:首頁 > 計算機 > java語言

Java數組的基本操作方法介紹

java語言2.22W

數組是具有相同數據類型的一組數據的集合,Java支持多為數組,一維數組的每個基本單元都是基本數據類型的數據,二維數組就是每個基本單元是一維數組的一維數組,以此類推,n維數組的每個基本單元都是n-1為數組的n-1維數組。下面以一維數組為例説明Java數組的用法。

Java數組的基本操作方法介紹

1、數組聲明

數組聲明有如下兩種形式(方括號的位置不同):

int arr[];int[] arr2;

2、數組初始化

數組初始化也有兩種形式,如下(使用new或不使用new):

int arr[] = new int[]{1, 3, 5, 7, 9};int[] arr2 = {2, 4, 6, 8, 10};

3、遍歷數組

遍歷數組可用for/foreach,如下:

public static void main(String[] args) { int arr[] = new int[]{1, 3, 5, 7 ,9}; int[] arr2 = {2, 4, 6, 8, 10}; for (int i = 0; i < th; ++i) { t(arr[i] + "t"); // 1 3 5 7 9 } for (int x: arr2) { t(x + "t"); // 2 4 6 8 10 } }

4、()填充數組

使用Arrays類的靜態方法,需要import包ys,定義了許多重載方法。

void fill(int[] a, int val)全部填充 void fill(int[] a, int fromIndex, int toIndex, int val)填充指定索引的元素 int[] arr3 = new int[5]; for (int x: arr3) { t(x + "t"); // 0 0 0 0 0 全部初始化為0 } tln(); (arr3, 10); for (int x: arr3) { t(x + "t"); // 10 10 10 10 10 全部填充為10 } tln(); (arr3, 1, 3, 8); for (int x: arr3) { t(x + "t"); // 10 8 8 10 10 填充指定索引 } tln();

5、()對數組排序

void sort(int[] a)全部排序 void sort(int[] a, int fromIndex, int toIndex)排序指定索引的'元素 int[] arr4 = {3, 7, 2, 1, 9}; (arr4); for (int x: arr4) { t(x + "t"); // 1 2 3 7 9 } tln(); int[] arr5 = {3, 7, 2, 1, 9}; (arr5, 1, 3); for (int x: arr5) { t(x + "t"); // 3 2 7 1 9 } tln();

6、Of()複製數組

int[] copyOf(int[] original, int newLength)複製數組,指定新數組長度 int[] copyOfRange(int[] original, int from, int to)複製數組,指定所複製的原數組的索引 int[] arr6 = {1, 2, 3, 4, 5}; int[] arr7 = Of(arr6, 5); // 1 2 3 4 5 int[] arr8 = OfRange(arr6, 1, 3); // 2 3 for (int x: arr7) { t(x + "t"); } tln(); for (int x: arr8) { t(x + "t"); } tln();

7、檢查數組中是否包含某一個值

String[] stringArray = { "a", "b", "c", "d", "e" };boolean b = st(stringArray)ains("a");tln(b);// true

先使用st()將Array轉換成List,這樣就可以用動態鏈表的contains函數來判斷元素是否包含在鏈表中。

8、連接兩個數組

int[] intArray = { 1, 2, 3, 4, 5 };int[] intArray2 = { 6, 7, 8, 9, 10 };// Apache Commons Lang libraryint[] combinedIntArray = ll(intArray, intArray2);

ArrayUtils是Apache提供的數組處理類庫,其addAll方法可以很方便地將兩個數組連接成一個數組。

9、數組翻轉

int[] intArray = { 1, 2, 3, 4, 5 };rse(intArray);tln(ring(intArray));//[5, 4, 3, 2, 1]

依然用到了萬能的ArrayUtils。

10、從數組中移除一個元素

int[] intArray = { 1, 2, 3, 4, 5 };int[] removed = veElement(intArray, 3);//create a new tln(ring(removed));