数组遍历: 就是将数组中的每个元素分别获取出来, 就是遍历. 遍历也是数组操作中的基石
代码实现:
- public class Demo03Array {
- public static void main(String[] args) {
- // 定义数组
- int[] arr = {1, 2, 3, 4, 5};
- // 遍历数组
- for (int i = 0; i <arr.length; i++) {
- // 打印数组中的具体元素
- System.out.println(arr[i]);
- }
- }
- }
执行结果:
数组获取最大值元素
最大值获取: 从数组的所有元素中找出最大值.
实现思路:
定义变量, 保存数组 0 索引上的元素
遍历数组, 获取出数组中的每个元素
将遍历到的元素和保存数组 0 索引上值的变量进行比较
如果数组元素的值大于了变量的值, 变量记录住新的值
数组循环遍历结束, 变量保存的就是数组中的最大值
代码实现:
- public class Demo04Array {
- public static void main(String[] args) {
- int[] arr = {5, 15, 2000, 10000, 100, 4000};
- // 定义变量, 保存数组中 0 索引的元素
- int max = arr[0];
- // 遍历数组, 取出每个元素
- for (int i = 0; i < arr.length; i++) {
- // 遍历到的元素和变量 max 比较
- // 如果数组元素大于 max
- if (arr[i]> max) {
- //max 记录住大值
- max = arr[i];
- }
- }
- System.out.println("数组最大值是:" + max);
- }
- }
执行结果
数组作为方法参数和返回值
数组作为方法参数传递, 传递的参数是数组内存的地址.
代码举例:
- public class Demo05Array {
- public static void main(String[] args) {
- int[] arr = {1, 3, 5, 7, 9};
- // 调用方法, 传递数组
- printArray(arr);
- }
- /*
- 创建方法, 方法接收数组类型的参数
- 进行数组的遍历
- */
- public static void printArray(int[] arr) {
- for (int i = 0; i < arr.length; i++) {
- System.out.println(arr[i]);
- }
- }
- }
数组作为方法的返回值, 返回的是数组的内存地址
- public class Demo06Array {
- public static void main(String[] args) {
- // 调用方法, 接收数组的返回值
- // 接收到的是数组的内存地址
- int[] arr = getArray();
- for (int i = 0; i < arr.length; i++) {
- System.out.println(arr[i]);
- }
- }
- /*
- 创建方法, 返回值是数组类型
- return 返回数组的地址
- */
- public static int[] getArray() {
- int[] arr = {11, 3,34, 5};
- // 返回数组的地址, 返回到调用者
- return arr;
- }
- }
执行结果:
总结:
方法的参数为基本类型时, 传递的是数据值. 方法的参数为引用类型时, 传递的是地址值.
数组常见错误
数组越界异常:
我们访问了数组中不存在的索引, 程序运行后, 将会抛出 ArrayIndexOutOfBoundsException 数组越界异常. 在开发中, 数组的越界异常是不能出现的, 一旦出现了, 就必须要修改我们编写的代码.
数组空指针异常:
数组变量 arr 没有保存数组的内存地址, 我在通过 arr 去操作数组, 程序运行的时候会抛出 NullPointerException 空指针异常. 在开发中, 数组的越界异常是不能出现的, 一旦出现了, 就必须要修改我们编写的代码.
来源: http://www.bubuko.com/infodetail-3054437.html