数组操作
1. 数组地址转移问题【难点】
public static void main(String[] args) {
int[] arr1 = new int[10];
int[] arr2 = new int[10];
arr1[0] = 10;
arr2[0] = 20;
System.out.println("arr1[0]:" + arr1[0]);
System.out.println("arr2[0]:" + arr2[0]);
arr1[5] = 50;
arr2 = arr1;
arr1[0] = 30;
arr2[0] = 100;
System.out.println("arr1[0]:" + arr1[0]);
System.out.println("arr2[0]:" + arr2[0]);
System.out.println("arr2[5]:" + arr2[5]);
/*
1. 报错
2. 30 30 50
3. 100 100 50 true
4. 30 100 50
5. 50 100 50
6. 30 100 0
*/
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0GNw7vdC-1587862980278)(D:\A___课件\NZ2005课件资料\第二周\Day10-数组操作\img\数组地址转移分析图.png)]
问题总结:
1.
int[] arr1 = new int[20];
int[] arr2 = new int[10];
arr1 = arr2;
arr1[15] ???; 错误的
arr1 和 arr2 执行的空间为同一个数组空间
2.
int[] arr1 = new int[10];
int[] arr2 = new int[10];
arr1[0] = 10;
arr2[0] = 20;
arr2[5] = 100;
arr1[0] = arr2[0];
arr1[0] ?
arr1[5] ?
20, 0
赋值操作完成的是对于元素直接内容的转换,不涉及数组地址转移
3.
是否可以展示数组中 arr[0] arr[5]元素的空间首地址
不好意思,不能!!!
2. 数组作为方法的参数
2.1 还是比葫芦画瓢
public static void main(String[] args) {
}
/*
(String[] args)
String[] args 就是给数组作为方法参数格式,这里main方法需要的参数是一个String 类型的数组
格式:
public static 返回值类型 方法名(数据类型[] 数组参数名)
数组是可以作为方法的返回值
【BUT】
在我没有演示,讲解数组作为返回值使用的情况下,任何人不得使用数组作为返回值
以防万一你遇到一些你想不到的错误!!!
*/
2.2 数组作为参数分析过程
/*
a. 在一个int类型数组中,存储的内容是1 ~ 10
int[] arr = {10, 8, 35, 67, 31, 25, 11, 30, 28, 99};
使用代码找出,元素 == 30 所在下标位置
找出元素30对应的下标位置
1. 这里需要利用循环遍历数组,查询操作
2. 查询结果不确定,有可能找到,有可能找不到
3. 在查询之前我们假设对应的数据时不存在的
-1 作为保存目标数据的初始值
方法分析:
固定格式:
public static 不要问
返回值类型:
void:
没有返回值,功能变成数据找到直接打印,没有返回到方法外,这是一个黑盒
方法。黑盒方法是数据传入之后,没有任何的返回
int:
返回指定元素的下标位置,没有找到返回-1
方法名:
indexOf
获取指定元素对应下标
形式参数列表:
int[] arr:
查询数据的源数组,在哪一个数组中进行查询操作,这里需要一个int类型数组
int find:
指定在数组中查询的元素
(int[] arr, int find)
方法声明:
public static int indexOf(int[] arr, int find)
*/
2.3 方法实现和文档注释
/**
* 在指定数组arr中,查询指定元素find所在的下标位置,找到返回值大于等于0,没有找到
* 返回-1
*
* @param arr 查询数据的源数据数组,int类型数组
* @param find 指定在数组中查询的数据,也是对应int类型
* @return 找到指定元素,返回值大于等于0,否则返回-1
*/
public static int indexOf(int[] arr, int find) {
// 假设查询的数据不存在
int index = -1;
// 遍历整个数组
for (int i = 0; i < arr