Java 中的数组
什么是 Java 数组?
Java 数组是一种非常常见的数据结构,它包含所有相同数据类型的数据值。放入数组中的数据项称为元素,数组中的第一个元素索引为零。数组继承了 Object 类,并实现了 Serializable 和 Cloneable 接口。我们可以在数组中存储原始值或对象。
简单来说,它是一种编程构造,可以用来替代这个
x0=0; x1=1; x2=2; x3=3; x4=4; x5=5;
变成这样…
x[0]=0; x[1]=1; x[2]=2; x[3]=3; x[4]=4; x[5]=5;
这样做的好处是,一个变量可以引用索引(方括号中的数字[])以便于循环。
for(count=0; count<5; count++) { System.out.println(x[count]); }
Java 中的数组类型
数组有两种类型。
- 一维数组
- 多维数组
数组变量
在程序中使用数组是一个3 步过程 –
1) 声明你的数组
2) 创建你的数组
3) 初始化你的数组
1) 声明你的数组
语法
<elementType>[] <arrayName>;
或
<elementType> <arrayName>[];
示例
int intArray[]; // Defines that intArray is an ARRAY variable which will store integer values int []intArray;
2) 创建数组
arrayname = new dataType[]
示例
intArray = new int[10]; // Defines that intArray will store 10 integer values
声明和创建结合
int intArray[] = new int[10];
3) 初始化数组
intArray[0]=1; // Assigns an integer value 1 to the first element 0 of the array intArray[1]=2; // Assigns an integer value 2 to the second element 1 of the array
声明并初始化数组
[] = {};示例
int intArray[] = {1, 2, 3, 4}; // Initilializes an integer array of length 4 where the first element is 1 , second element is 2 and so on.
第一个数组程序
步骤 1) 将以下代码复制到编辑器中。
class ArrayDemo{ public static void main(String args[]){ int array[] = new int[7]; for (int count=0;count<7;count++){ array[count]=count+1; } for (int count=0;count<7;count++){ System.out.println("array["+count+"] = "+array[count]); } //System.out.println("Length of Array = "+array.length); // array[8] =10; } }
步骤 2) 保存、编译和运行代码。观察输出
预期输出
array[0] = 1 array[1] = 2 array[2] = 3 array[3] = 4 array[4] = 5 array[5] = 6 array[6] = 7
步骤 3) 如果 x 是对数组的引用,x.length 将给出数组的长度。
取消注释第 10 行。保存、编译和运行代码。观察输出
Length of Array = 7
步骤 4) 与 C 不同,Java 在访问数组元素时会检查边界。Java 不允许程序员超出其边界。
取消注释第 11 行。保存、编译和运行代码。观察输出
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8 at ArrayDemo.main(ArrayDemo.java:11) Command exited with non-zero status 1
步骤 5) 抛出 ArrayIndexOutOfBoundsException。在 C 的情况下,相同的代码将显示一些垃圾值。
Java 数组:传引用
数组通过引用(或指针)传递给函数
原始数据。这意味着你在函数内部对数组所做的任何操作
都会影响原始数据。
示例:理解数组是通过引用传递的
第 1 步: 将以下代码复制到编辑器中
class ArrayDemo { public static void passByReference(String a[]){ a[0] = "Changed"; } public static void main(String args[]){ String []b={"Apple","Mango","Orange"}; System.out.println("Before Function Call "+b[0]); ArrayDemo.passByReference(b); System.out.println("After Function Call "+b[0]); } }
步骤 2) 保存、编译和运行代码。观察输出
预期输出
Before Function Call Apple After Function Call Changed
多维数组
多维数组实际上是数组的数组。
要声明多维数组变量,请为每个附加维度使用另一组方括号。
Ex: int twoD[ ][ ] = new int[4][5] ;
当你为多维数组分配内存时,你只需要为第一个(最左边的)维度指定内存。
你可以单独分配剩余的维度。
在 Java 中,多维数组中每个数组的长度都由你控制。
示例
public class Guru99 { public static void main(String[] args) { // Create 2-dimensional array. int[][] twoD = new int[4][4]; // Assign three elements in it. twoD[0][0] = 1; twoD[1][1] = 2; twoD[3][2] = 3; System.out.print(twoD[0][0] + " "); } }
预期输出
1