大家好,欢迎来到IT知识分享网。

如果你想定义一个数组,包含 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 作者:廖雪峰
完
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/178911.html