数组是存储同一类型数据的数据结构
数组的声明与初始化
int[] a; int a[];int[] a = new int[100];
int[] a = new int[100];for (int i = 0; i < 100; i++)
a[i]= i; //fills the array with numbers 0 to 99
一旦创建就不可改变其大小
3.10.1 for each 循环
for each循环可以用来为数组赋值
for (variable : collection) statement
int[] a = new int[100] ;
for (intelement : a)
System.out.println(element);
对数组a的每个 element 输出。
如果想直接输出数组,可以使用Arrays(java.util.Arrays )类的toString方法。
System.out.println(Arrays.toString(a));
3.10.2 数组初始化与匿名数组
int[] smallPrimes = { 2, 3, 5, 7, 11, 13};
匿名数组初始化:new int[] { 17, 19, 23, 29, 31, 37}
smallPrimes= new int[] { 17, 19, 23, 29, 31, 37};
是int[] anonymous = { 17, 19, 23, 29, 31, 37};
smallPrimes=anonymous;
的简写
3.10.3 复制数组
int[] copiedLuckyNumbers = Arrays.copyOf(luckyNumbers, luckyNumbers.length);
如果长度超出,赋值为0.
3.10.4 命令行参数
如果执行程序时使用命令 java Message -g cruel world
那么在main函数中即可接受
args[0]: "-g"args[1]: "cruel"args[2]: "world"
public classMessage
{public static voidmain(String[] args)
{if (args.length == 0 || args[0].equals("-h"))
System.out.print("Hello,");else if (args[0].equals("-g"))
System.out.print("Goodbye,");//print the other command-line arguments
for (int i = 1; i < args.length; i++)
System.out.print(" " +args[i]);
System.out.println("!");
}
}
3.10.5 数组排序
int[] a = new int[10000];
. . .
Arrays.sort(a)
3.10.6 多维数组
double[][] balances;
int[][] magicSquare ={
{16, 3, 2, 13},
{5, 10, 11, 8},
{9, 6, 7, 12},
{4, 15, 14, 1}
};
for (double[] row : a)for (doublevalue : row)do something with value
System.out.println(Arrays.deepToString(a));快速输出2多维数组
3.10.7 不规则数组(Ragged Arrays)
Java中其实没有严格意义的多维数组,他是用数组存储的数组,每个一维数组的元素个数可以不同,类型也可不同。