数组中 Java
什么是 Java 数组?
Java 排列 是一种非常常见的数据结构,它包含相同数据类型的所有数据值。放入数组中的数据项称为元素,数组中的第一个元素从索引零开始。数组继承对象类并实现可序列化和可克隆接口。我们可以将原始值或对象存储在数组中。
简单来说,它是一种编程结构,可以帮助取代这个
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>;
or
<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.长度 将为您提供数组的长度。
取消注释第 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] ;
为多维数组分配内存时,仅需指定第一维(最左边)的内存。
您可以单独分配剩余的尺寸。
In 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