数组是每一门编程语言中都很重要的一种数据类型(数据结构)。
java 中提供的数组这种数据结构用来存储**固定个数
的一个或多个相同类型
**的元素。
数组的声明
数组声明有两种方法
public class ArrTest {
public static void main(String[] args) {
int[] arr;
}
}
这里 int 指定了数组只能存储 int 类型的数据。 2.
public class ArrTest {
public static void main(String[] args) {
int arr[];
}
}
创建数组
java 使用new
操作符来创建数组,语法如下:
dataType[] arrayName = new dataType[length];
或者:
dataType[] arrayName = {v1, v2, v3, ...};
举例:
public class ArrTest {
static int sumFn(int[] arr) {
// int sum; // 报错:因为sum是存在于sunFn方法中的局部变量,局部变量没有默认值,必须经过初始化才能够使用
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
public static void main(String[] args) {
int[] arr = new int[10];
String[] strs = { "1", "2", "3" };
for (int i = 0; i < arr.length; i++) {
arr[i] = i * 10;
}
System.out.println(arr[5]); // 5
System.out.println(strs[2]); // 3
System.out.println(ArrTest.sumFn(arr)); // 450
}
}
For-Each 循环
java 中可以使用 For-Each 循环遍历数组,他能在不使用下标的情况下遍历数组:
public class ArrForEach {
public static void main(String[] args) {
int[] arr = { 1, 5, 9, 8, 3, 15, 6, 3, 4, 65 };
for (int val : arr) {
System.out.println(val);
}
}
}
易错:
public class Practice {
static void doIt(int[] z) {
z = null;
System.out.println(z); // null
}
public static void main(String[] args) {
int[] myArray = { 1, 2, 3, 4, 5 };
Practice.doIt(myArray);
for (int j = 0; j < myArray.length; j++) {
// 最终会输出 1 2 3 4 5
System.out.print(myArray[j] + " ");
}
}
}
在这个程序中System.out.print( myArray[j] + " " );
语句会正常输出myArray
的5个元素。因为在ChangeIt.doIt
方法中,z = null;
语句只是表示z这个引用不再指向任何对象(内存地址),并不会对原先的数据进行修改。