數組是一種資料結構,其聲明方式如下:
type[] arrayName;
數組具有以下屬性:
1.數組可以是一維、多維或交錯的。
2.數值數組元素的預設值設定為零,而引用元素的預設值設定為 null。
3.交錯數組是數組的數組,因此,它的元素是參考型別,初始化為 null。
4.數組的索引從零開始:具有 n 個元素的數組的索引是從 0 到 n-1。
5.數組元素可以是任何類型,包括數群組類型。
一維數組
程式碼
//聲明一維數組,沒有初始化,等於null
int[] intArray1;
//初始化已聲明的一維數組
intArray1 = new int[3]; //數組元素的預設值為0
intArray1 = new int[3]{1,2,3};
intArray1 = new int[]{1,2,3};
//聲明一維數組,同時初始化
int[] intArray2 = new int[3]{1,2,3};
int[] intArray3 = new int[]{4,3,2,1};
int[] intArray4 = {1,2,3,4};
string[] strArray1 = new string[]{"One","Two","Three"};
string[] strArray2 = {"This","is","an","string","Array"};
多維陣列
程式碼
//聲明二維數組,沒有初始化
short[,] sArray1;
//初始化已聲明的二維數組
sArray1 = new short[2,2];
sArray1 = new short[2,2]{{1,1},{2,2}};
sArray1 = new short[,]{{1,2,3},{4,5,6}};
//聲明二維數組,同時初始化
short[,] sArray2 = new short [1,1]{{100}};
short[,] sArray3 = new short [,]{{1,2},{3,4},{5,6}};
short[,] sArray4 = {{1,1,1},{2,2,2}};
//聲明三維數組,同時初始化
byte[,,] bArray1 = {{{1,2},{3,4}},{{5,6},{7,8}}};
交錯數組
程式碼
//聲明交錯數組,沒有初始化
int[][] JagIntArray1;
//初始化已聲明的交錯數組
JagIntArray1 = new int [2][] {
new int[]{1,2},
new int[]{3,4,5,6}
};
JagIntArray1 = new int [][]{
new int[]{1,2},
// new int []{3,4,5},
intArray2 //使用int[]陣列變數
};
//聲明交錯數組,同時初始化
int[][] JagIntArray2 = {
new int[]{1,1,1},
//new int []{2,2},
intArray1
};