Skip to content

数组

数组是一种引用数据类型。

声明

声明格式:type[] variable,表示声明了一个数组用于存储 type 类型数据。

如,int[] x表示声明一个数组用于存储 int 类型数据。

初始化

数组的初始化分为两种:静态初始化和动态初始化。

静态初始化

静态初始化的格式:type[] variable = new type[size]{value1, value2, ..., valuex}

也可以这样写:type[] variable = {value1, value2, ..., valuex}

以上格式表示,声明了数组用于存储 type 类型数据,数组长度为 size,数组成员分别是value1, value2, ..., valuex,并将数组的引用赋值给变量名 variable。

java
public class Demo{
	public static void main(String[] args){
		int[] arr = new int[5]{10, 20, 30, 40, 50};
		// 另一种写法
		int[] arr = {10, 20, 30, 40, 50}; 
	}
}

动态初始化

动态初始化的格式:type[] variable = new type[size]

java
public class Demo{
	public static void main(String[] args){
		int[] arr = new int[5];
	}
}

静态初始化和动态初始化的区别在于定义数组时,是否有数组成员。

数组遍历

数组的遍历有两种方式:基本遍历和 forEach 遍历。

基本遍历

java
public class Demo{
	public static void main(String[] args){
		int[] arr = {10, 20, 30, 40, 50};
		for(int index = 0; index < arr.length; i++) {
			System.out.println(arr[index]);
		}
	}
}

优点:

  • 可以通过索引访问数组的每一项,能对数组的每一项进行取值赋值操作

缺点:

  • 写法麻烦

forEach 遍历

java
public class Demo{
	public static void main(String[] args){
		int[] arr = {10, 20, 30, 40, 50};
		for(int item : arr) {
			System.out.println(item);
		}
	}
}

优点:

  • 写法容易

缺点:

  • 只有一个变量用来表示数组的每一项,没有索引,只能对数组的每一项进行取值操作,不能进行赋值操作