简单数组
声明与创建
首先必须声明数组变量,才能在程序中使用数组。下面是声明数组变量的语法:
dataType[] arrayRefVar; // 首选的方法
dataType arrayRefVar[]; // 效果相同,但不是首选方法
注意,建议使用
创建数组
arrayRefVar = new dataType[arraySize];
上面的语法语句做了两件事,首先是使用 dataType[arraySize]
创建了一个数组,然后把新创建的数组的引用赋值给变量
dataType[] arrayRefVar = new dataType[arraySize];
dataType[] arrayRefVar = {value0, value1, ..., valuek};
数组与函数
数组可以作为参数传递给方法。例如,下面的例子就是一个打印
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
// 数组作为函数的返回值
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
遍历检索
循环
数组的元素类型和数组的大小都是确定的,所以当处理数组元素时候,我们通常使用基本循环或者
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// 打印所有数组元素
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// 计算所有元素的总和
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// 查找最大元素
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
for(type element: array)
{
System.out.println(element);
}
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// 打印所有数组元素
for (double element: myList) {
System.out.println(element);
}
}
}
多维数组
多维数组可以看成是数组的数组,比如二维数组就是一个特殊的一维数组,其每一个元素都是一个一维数组,例如:
String str[][] = new String[3][4];
多维数组的动态初始化
直接为每一维分配空间,格式如下:
type[][] typeName = new type[typeLength1][typeLength2];
int a[][] = new int[2][3];
二维数组
String s[][] = new String[2][];
s[0] = new String[2];
s[1] = new String[3];
s[0][0] = new String("Good");
s[0][1] = new String("Luck");
s[1][0] = new String("to");
s[1][1] = new String("you");
s[1][2] = new String("!");
多维数组的引用(以二维数组为例)
对二维数组中的每个元素,引用方式为
num[1][0];