天天看點

Arrays 類及基本使用

主要方法

  • static type[] copyof(type[] original,int length)
  • static int binarysearch(type[] a,type key)
  • static boolean equals(type[] a,type[] b)
  • static void fill(type[] a,type val)
  • static void fill(type[] a,int fromindex,int toindex,type val)
  • static void sort(type[] a)

執行個體代碼

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

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

package Arrays;

import java.text.Collator;

import java.util.Arrays;

import java.util.Comparator;

public class ArraysDemo {

public static void main(String agrs[]) {

Integer arr[]=new Integer[9];

for(int i=0;i<9;i++)

arr[i]=(int)(Math.random()*100);

//顯示,排序數組

System.out.print("原内容:");

display(arr);

Arrays.sort(arr);

System.out.print("排序後:");

display(arr);

//将值-1 配置設定給數組 arr 中下标從 0 到 3-1 的位置

Arrays.fill(arr, 0,3,-1);

System.out.print("fill() 後:");

display(arr);

//搜尋 23

System.out.print("值 23 的位置:");

int index =Arrays.binarySearch(arr, 23);//二分查找

System.out.print(index);//如果查找不到,index 為負

System.out.print("\n 插入 0 在 3 号位置:");

Arrays.fill(arr,3,4,0);

display(arr);

System.out.print("值 0 的位置:");

index =Arrays.binarySearch(arr, 0);

System.out.print(index);

Integer arr2[]=new Integer[8];

arr2=Arrays.copyOf(arr, arr2.length);

//複制 8 個

System.out.print("\n 複制後的數組:");

display(arr2);

if(Arrays.equals(arr, arr2))

System.out.println("兩數組相同!");

else System.out.println("兩數組不相同!");

System.out.println("----------------------------------------");

String[] str = {"計算機","黃桑","通信","李瑞豪"};

Arrays.sort(str);

for(int i=0;i<str.length;i++)

System.out.print(str[i]+" ");

System.out.println("");

//Collator 類是用來執行分語言環境的字元串比較,這裡用的 CHINA

Comparator com=Collator.getInstance(java.util.Locale.CHINA);//擷取 Comparator 對象,參數表示按中文排序

//根據指定的 "比較器" 産生的順序對 "指定對象數組" 進行排序

Arrays.sort(str,com);//sort(T[] a,Comparator<?super T>c)

for(int i=0;i<str.length;i++)

System.out.print(str[i]+" ");

}

static void display(Integer arr[]) {

for(int i=0;i<arr.length;i++)

System.out.print(arr[i]+" ");

System.out.println("");

}

}

程式運作結果

1

2

3

4

5

6

7

8

9

10

11

原内容:41 0 44 96 49 96 30 6 87

排序後:0 6 30 41 44 49 87 96 96

fill() 後:-1 -1 -1 41 44 49 87 96 96

值 23 的位置:-4

插入 0 在 3 号位置:-1 -1 -1 0 44 49 87 96 96

值 0 的位置:3

複制後的數組:-1 -1 -1 0 44 49 87 96

兩數組不相同!

----------------------------------------

李瑞豪 計算機 通信 黃桑

黃桑 計算機 李瑞豪 通信