组团学

数组常用操作

阅读 (3419432)

1、数组常用操作

1.1、数组遍历

在操作数组时,经常需要依次访问数组中的每个元素,这种操作称作数组的遍历。

案例:

public class ArrDemo05 { public static void main(String[] args) { int[] arr = { 1, 2, 3, 4, 5 };// 定义数组 //使用for循环遍历数组的元素 for(int i = 0; i < arr.length; i++) { System.out.println(arr[i]);// 通过索引访问元素 } } }

运行结果:

image20191206115953636.png

1.2、数组获取最大值元素

从数组的所有元素中找出最大的元素

案例:

/* 分析: 定义变量,保存数组0索引上的元素 遍历数组,获取出数组中的每个元素 将遍历到的元素和保存数组0索引上值的变量进行比较 如果数组元素的值大于了变量的值,变量记录住新的值 数组循环遍历结束,变量保存的就是数组中的最大值 */ public class ArrDemo06{ 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); } }

运行结果

image20191206135341187.png

1.3、数组反转

数组中的元素颠倒顺序,例如原始数组为1,2,3,4,5,反转后的数组为5,4,3,2,1

案例:

public class ArrDemo07 { public static void main(String[] args) { int[] arr = { 1, 2, 3, 4, 5 }; /* 循环中定义变量min=0最小索引 max=arr.length‐1最大索引 min++,max‐‐ */ for (int min = 0, max = arr.length-1; min <= max; min++,max--){ //利用第三方变量完成数组中的元素交换 int temp = arr[min]; arr[min] = arr[max]; arr[max] = temp; } // 反转后,遍历数组 for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } } }

运行结果:

image20191206135830191.png

1.4、数组作为方法参数

数组作为方法参数传递,传递的参数是数组内存的地址。

案例:

public class ArrDemo08{ 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]); } } }

运行结果:

image20191206140547568.png

1.5、数组作为方法返回值

数组作为方法的返回值,返回的是数组的内存地址 。

案例:

public class ArrDemo09{ 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 = { 1, 3, 5, 7, 9 }; //返回数组的地址,返回到调用者 return arr; } }

运行结果:

image20191206140959367.png

2、数组注意事项

2.1、数组的长度是固定的

数组在创建对象过程当中,必须指定数组长度,如果无法指定,就无法创建对象进而无法给变量赋值。

2.2、一个数组中只能存储一种类型的数据

在数组的定义格式中有显式地写出该数组中存储的数据类型,所以一个数组只能存储同一种数据类型。

2.3、数组下标越界

当数组中不存在该索引却访问该索引时,运行时报错:ArrayIndexOutOfBoundsException 数组索引越界

案例观察:

public class ArrDemo10{ public static void main(String args[]){ int arr[]={1,2,3}; System.out.println(arr[3]); } }

运行结果:

image20191206114643430.png

6.4、空指针异常

当数组中如果将该数组赋值为null,运行时报错:NullPointerException 空指针异常

案例观察:

public class ArrDemo11 { public static void main(String args[]){ int arr[]=new int[5]; arr=null; System.out.println(arr[0]); } }

运行结果:

image20191206115136055.png

需要 登录 才可以提问哦