数组
1,一维数组
声明:
数组元素类型 数组名字[];
数组元素类型[] 数组名字;
分配内存:
数组名字 = new 数组元素的类型[数组元素的个数];
//使用new关键字为数组分配内存时,整型数组中各个元素的初始值都为0
声明同时分配内存:
数组元素的类型 数组名 = new 数组元素的类型[数组元素的个数];
初始化:
int arr[] = new int[]{1, 2, 3, 4, 5};
int arr2[] = {1, 2, 3};
2,二维数组
声明:
数组元素类型 数组名字[][];
数组元素类型[][] 数组名字;
分配内存:
数组名字 = new 数组元素的类型[数组元素的个数][数组元素的个数];
//使用new关键字为数组分配内存时,整型数组中各个元素的初始值都为0
声明同时分配内存:
数组元素的类型 数组名 = new 数组元素的类型[数组元素的个数][数组元素的个数];
初始化:
type arrName[][] = {val1, val2, ... ,valn};
//type:数组数据类型
//arrName:数据名称
//val:数组中各元素的值
int myarr[][] = {{1,2}, {3,4}};
3,遍历数组
使用for循环,一维数组使用一层for循环,二维数组使用双层for循环
4,填充替换数组元素
下面所用到的arr为一个数组
int[] arr = new int[] {1, 2, 3};
1,fill(int[] a, int val)
将指定的int值分配给int型数组的每个元素
arr.fill(int[] a, int val);
//a:要进行元素替换的数组
//val:要存储数组中所有元素的值
2,fill(int[] a, int fromIndex, int toIndex, val)
将指定的int值分配给int型数组指定范围中的每个元素。填充范围从fromIndex一直索引到toIndex,左闭右开区间,如果fromIndex==toIndex,则填充范围为空
arr.fill(int[] a, int fromIndex, int toIndex, val);
//a:要进行填充的数组
//fromIndex:第一个索引(包括)
//toIndex:第二个索引(不包括)
//val:要存储的值
5,对数组排序
Arrays.sort(object)
object是指进行排序的数组名称
默认从小到大排序
Arrays.sort(arr);
6,复制数组
1,copyOf()
int[] newArr = Arrays.copyOf(arr, int newlen);
//arr:要复制的数组
//newlen:复制后新数组的长度,如果大于arr的长度,补零;如果小于arr的长度,舍去
2,copyOfRange()
int newArr = Arrays.copyOfRange(arr, int formIndex, int toIndex);
//arr:要复制的数组
//formIndex:起始索引(包括)
//toIndex:结束索引(不包括),如果越界就补零
7,数组查询
二分搜索,必须为有序数组
1,binarySearch(Object[], Object key)
int index = Arrays.binarySearch(Object[] a, Object key);
//a:要搜索的数组
//key:要搜索的值
//如果key在a中,返回索引,否则返回-1或“-”(插入点)
2,binarySearch(Object[], int st, int ed, Object key)
int index = Arrays.binarySearch(Object[] a, int st, int ed, Object key);
//a:要搜索的数组
//st:开始索引(包含)
//ed:结束索引(不包含)
//key:要搜索的值
//如果key在a中,返回索引,否则返回-1或“-”(插入点)