4.6 toString(相当于遍历,得到数组的字符串表示)
6.1 下标越界异常(ArrayIndexOutOfBoundsException)
6.2 空指针异常(NullPointerException)
1 定义
数组是一组具有相同类型的元素的集合。
2 初始化
int[] a;
表示定义一个a,类型是存在int类型元素的数组,大小不确定。
int[] a = {1,2,3,4,5};
表示定义一个变量a,其类型是数组,该数组的元素类型是int,该数 组进行了初始化操作,数组大小确定为五个,元素分别是1,2,3,4,5.
int[] a =new int [] {1,2,3,4,5};
boolean[] a = {true,false};
String[] a = {"Hello ","World"};
String[] a = new String[] {"A","B"};
Random[] a = { new Random(),new Random(),new Random()};
int[] a = new int[3];
定义一个数组,元素个数为三;该式等价于 int[] a = new int[] {0,0,0}
String[] a = new String[3];
该式等价于 String[] a = new String[] {null,null,null};
注意:int[] a; a = {1,2,3,4,5}; 这种用法是错误的,不能使用这个语法
int[] a; a = new int[] {1,2,3}; 而这种语法是正确的
注意:数组的长度一旦确定是无法更改的。
int[] a = new int[3]; //定义一个有三个元素的数组,让a引用指向该数组
a = new int[5]; //定义一个新的有五个元素的数组,让a引用指向新的数组
上面这种写法是可以的,本质上数组长度没有变,只是改变了a的引用指向。
int[] a = {1,2,3};
int[] b = new int[]{1,2,3,4};
b = new int[]{4,5};
int[] c = new int[5];
int[] c = new int[3]; //改变c的指向,并不意味着改变了数组的长度
3 下标访问
- 数组下标的类型为int类型,其下标范围为[0,数组的长度)。
- 使用下标访问数组元素的具体代码:
a[下标] = 0; //将该位置的元素赋值为0;
b = a[下标]; //将该位置的元素赋值给另一个变量
4 常见操作
4.1 sort(排序操作)
4.1.1 Java实现
Arrays.sort(array);//实现对数组的全排操作
Arrays.sort(array,1,5);//将数组下标为一到4的元素进行排序,其余位置不变
4.1.2 自实现
public static void MySort(long[] array,int fromIndex,int toIndex){
int size = toIndex - fromIndex;
for(int i = 0;i < size - 1;i++){
for(int j = fromIndex;j < toIndex - i - 1;j++){
if(array[j] > array[j + 1]){
swap(array,j,j+1);
}
}
// for(int j = 0;j < size - i - 1;j++){
// if(array[fromIndex + j] > array[fromIndex + j + 1]){
// swap(array,fromIndex + j,fromIndex + j + 1);
// }
// }
}
}
public static void swap(long[] array,int x,int y){
long t =