在 Java 中使用数组

在 Java 中使用数组

经验文章nimo972025-05-21 2:14:181A+A-

如果你想定义一个数组,包含 5 个整数类型,可以这么写:

int[] arr = new int[5];
arr[0] = 42; // 为第一个元素赋值为 42
arr[1] = 60; // 为第二个元素赋值为 60

如果想遍历数组所有元素,可以使用 for 循环:

for (int i = 0; i < arr.length; i++) {
  System.out.println(arr[i]);
}

如果访问的索引超过数组范围,Java 编译器会报错(数组越界异常):

int[] arr = new int[5];
arr[100] = 250;
// Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 
// Index 100 out of bounds for length 5

定义数组时,可以使用花括号中的元素填充,此时,无需指定数组长度,其值可被自动计算。

int[] arr = new int[] { 6, 5, 4, 3 };
System.out.println(arr.length); // 4

// 还可以简化为如下形式
int[] arr = { 6, 5, 4, 3 };

字符串数组这么写:

String[] heroes = {
  "Tony Stack",
  "Peter Parker",
  "Steve Rogers"
};

数组本身是一种引用类型,字符串自身也是一种引用类型,因此,字符串数组属于“双重”引用类型。

参考资料


https://liaoxuefeng.com/books/java/quick-start/basic/array/index.html 作者:廖雪峰

点击这里复制本文地址 以上内容由nimo97整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

尼墨宝库 © All Rights Reserved.  蜀ICP备2024111239号-7