1. 程式人生 > 實用技巧 >【製作】基於金沙灘51微控制器的電子密碼鎖程式

【製作】基於金沙灘51微控制器的電子密碼鎖程式

Java陣列

定義:

  • 是相同型別資料的有序集合

  • 是相同型別的若干個資料,按一定先後順序排列組合而成。

  • 每個資料稱作陣列元素,每個陣列元素可通過下標訪問。

申明建立:

  • 寫法:

    • int[] nums; nums=new int[10];

    • int nums[];

記憶體分配示意圖:

三種初始化:

  • 靜態初始化

int[] a ={1,2,3};
Man[] mans = {new Man(1,1),new Man(2,2)};
  • 動態初始化(預設初始化)

int[] a =new int[2];
a[0]=1;
a[1]=2;
  • 陣列的預設初始化

    • 陣列是引用型別,它的元素相當於類的例項變數,因此陣列一經分配空間,其中每個元素也被安裝例項變數同樣的方式被隱式初始化。

四個基本特點:

  • 長度是確定的。

  • 所有元素型別都是相同的,不允許出現混合型別。

  • 陣列中的元素可以是任何資料型別,可以是基本型別或引用型別。

  • 陣列變數屬於引用型別,陣列也可看成是物件。陣列本身就是物件,Java中物件是在堆中的,因此陣列無論儲存原始型別還是其他物件型別,陣列物件本身就是在堆中

陣列使用:

package com.chenhao.method;
public class Demo07 {
public static void main(String[] args) {
int[] num1s = {1,2,3,4,5,6};
int[] num2s = new int[10];
print(num1s);
int[] b = array(num1s);
print(b);
}
public static int[] array(int[] sorry){
int[] a = new int[sorry.length];
for (int i = 0,j = sorry.length - 1; i < sorry.length; i++,j--) {
a[j] = sorry[i];
}
return a;
}
public static void print(int[] age){
for (int i : age) {
System.out.print(i+" ");
}
System.out.println();
}
}

二維陣列:

即一維數組裡套用一維陣列。

package com.chenhao.method;
public class Demo08 {
public static void main(String[] args) {
int[][] a = new int[3][3];
int[][] b = {{1,2},{3,4},{5,6},{7,8}};
for (int i = 0; i <b.length ; i++) {
for (int j = 0; j <b[i].length ; j++) {
System.out.print(b[i][j]+" ");
}
System.out.println();
}
}
}