Java 中遍历数组的不同方法?
一般来说,数组是存储多个相同数据类型变量的容器。它们的大小是固定的,并在创建时确定。数组中的每个元素都由从 0 开始的数字来定位。
您可以使用名称和位置访问数组的元素,如下所示:
System.out.println(myArray[3]); //Which is 1457
在 Java 中创建数组
在 Java 中,数组被视为引用类型,您可以使用 new 关键字类似于对象创建数组,并使用索引填充它,如下所示:
int myArray[] = new int[7]; myArray[0] = 1254; myArray[1] = 1458; myArray[2] = 5687; myArray[3] = 1457; myArray[4] = 4554; myArray[5] = 5445; myArray[6] = 7524;
或者,您可以直接在花括号内分配值,并用逗号 (,) 分隔它们,如下所示:
int myArray = { 1254, 1458, 5687, 1457, 4554, 5445, 7524};
遍历数组
您可以使用 for 循环或 forEach 循环遍历数组。
使用 for 循环 - 您可以使用 for 循环迭代索引,从 0 开始到数组的长度 (ArrayName.length),并在每个索引处访问元素,而不是逐个打印元素。
Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.
示例
public class IteratingArray { public static void main(String args[]) { //Creating an array int myArray[] = new int[7]; //Populating the array myArray[0] = 1254; myArray[1] = 1458; myArray[2] = 5687; myArray[3] = 1457; myArray[4] = 4554; myArray[5] = 5445; myArray[6] = 7524; //Printing Contents using for loop System.out.println("Contents of the array: "); for(int i=0; i<myArray.length; i++) { System.out.println(myArray[i]); } } }
输出
Contents of the array: 1254 1458 5687 1457 4554 5445 7524
使用 for each 循环 - 自 JDK 1.5 以来,Java 引入了一种新的 for 循环,称为 foreach 循环或增强型 for 循环,它使您能够在不使用索引变量的情况下顺序遍历整个数组。使用此方法,您可以更轻松地遍历数组。
示例
import java.util.Arrays; public class IteratingArray { public static void main(String args[]) { //Creating an array int myArray[] = new int[7]; //Populating the array myArray[0] = 1254; myArray[1] = 1458; myArray[2] = 5687; myArray[3] = 1457; myArray[4] = 4554; myArray[5] = 5445; myArray[6] = 7524; //Printing Contents using for each loop System.out.println("Contents of the array: "); for (int element: myArray) { System.out.println(element); } } }
输出
Contents of the array: [1254, 1458, 5687, 1457, 4554, 5445, 7524]
广告