1;创建数组
1)先声明,再用new进行内存分配
int arr[]; //一维数组
String str[];
int myarr[][]; //二维数组
这样声明数组只是给出了数组的名字和元素的数据类型,还要为它分配内存空间(使用new关键字)。在为数组分配内存空间时必须指明数组的长度。
arr = new int[5]; //一维数组
//二维数组
myarr = new int[2][4]; //直接为每一维分配内存
myarr = new int[2][]; //分别为每一维分配内存
myarr[0] = new int[3];
myarr[1] = new int[5];
//使用new关键字为数组分配内存时
//整型数组中各个元素初始值都是0
2) 声明的同时为数组分配内存
int month[] = new int[12];
int date[][] = new int[12][31];
2;初始化
//一维数组
int arr1[] = new int[]{1,2,3,4,5};
int arr2[] = {1,2,3,4};
//二维数组
int myarr[][] = {{1,2,3},{3,4,5,6}}; //为每一维分配内存的数组
3;数组的基本操作
1)遍历数组时,foreach语句更简单
2)对数组元素进行替换--Arrays类的静态方法fill()---在原数组上,不建立新的内存
(int[] a, int value);-------将指定的value分配给数组的每个元素
ill(int[] a, int formIndex, int toIndex, int value);---------填充范围为从fromIndex到(toIndex-1)
import ;
public class arrayDemo{
public static void main(String[] args){
int arr1[] = new int[5];
(arr1,7); //使用同一个值对数组进行填充替换
(arr2,0,3,7); //指定范围
for(int x:arr1){
("x"); //输出7,7,7,7,7
}
for(int x:arr2){
("x"); //输出7,7,7,0,0
}
}
}
4;对数组进行排序---Arrays类就静态sort()方法-----可对任意类型数组,升序排序,在原数组上,不建立新的内存
(object); //object为要被排序的数组
数字在字母之前,大写在小写之前
5;复制数组
1)copyOf()方法---复制数组至指定长度----开辟新的内存空间,原数组不变
-----若大于原数组长度,整型数组用0填充,char型数组用null来填充
copyOfRange()方法---将指定数组的制定出藏毒复制到一个新的数组中---原数组不变
(arr, int newlength);
(arr, int fromIndex, int toIndex); //范围为从fromIndex到(toIndex-1);
import ;
public class arrayDemo{
public static void main(String[] args){
int arr1[] = new int[]{1,2,3};
int arr2[] = new int[]{1,2,3,4,5};
int newarr1[] = (arr1,5); //copyOf()方法
int newarr2[] = (arr2,1,4); //copyOfRange()方法
for(int x:newarr1){
("x"); //输出1,2,3,0,0
}
for(int x:newarr2){
("x"); //输出2,3,4
}
}
}
6;数组查询
Arrays类的binarySearch()方法---用二分搜索法搜索指定数组---返回要搜索元素的索引值---适用于各种类型数组
-----必须在调用之前对数组进行排序(通过sort()方法)---如果数组包含多个带有指定值的元素,则无法保证找到的是哪一个
1)(Object[], Object key);
如果key包含在数组中,返回索引值;否则返回“-1”或“-”(插入点)
插入点:搜索键将要插入数组的那一点,即第一个大于此键的元素索引
2)(Object[], int fromIndex,int toIndex,Object key);
搜索范围为从fromIndex到(toIndex-1)
异常:如果指定的范围为大于或等于数组的长度,则会报出ArrayIndexOutOfBoundsException异常
import ;
public class arrayDemo{
public static void main(String[] args){
String str[] = new String[]{"ab","cd","ef","gh"};
(str); //必须先将数组排序
int index1 = (str,"cd"); //为1
int index2 = (str,"de");
//返回插入点
int index3 = (str,0,2,"cd"); //为1
}
}