一、数组的定义
引用数据类型,数组的地址连续,一旦创建长度固定,数组的地址是第一个元素的地址
-
动态初始化
数组类型 数组名 = 数组[长度]int[] arr = new int[5];
arr[0]=1; -
静态初始化
数组类型 数组名 = {}int[] arr = {1,2,3,4};
二、数组存储引用数据类型
Cat c1 = new Cat();
Dog d1 = new Dog();
Animal[] anis = {c1,d1};
//向下转型调用子类特有的方法
for (int i = 0; i < anis.length; i++) {
anis[i].move;
/**
* anis[i] instanceof Cat 子类
*/
if (anis[i] instanceof Cat){
Cat c11 = (Cat)anis[i];
c11.show();
}else if (anis[i] instanceof Dog){
Dog d11 = (Dog)anis[i];
d11.work();
}
}
}
class Animal{
public void move(){
System.out.println("move...");
}
}
class Cat extends Animal{
public void show(){
System.out.println("zoumaobu");
}
}
class Dog extends Animal{
public void work(){
System.out.println("kanmen");
}
}
三、数组的扩容
新建一个大容量的数组将小容量的数组遍历然后进行数组的拷贝
arraycopy 数组拷贝( 地址的指向变化)
String[] arr = {"hello ","java","world"};
String[] dest = new String[3];
// 源数组,位置,目标数组,目标开始位置,长度
System.arraycopy(arr,0,dest,0,arr.length);
for (String s : dest) {
System.out.println(s);
}
}
四、二维数组
//二维数组使用{}来分割每个元素,不过每个元素是一个数组
int[][] scores = {{78,80,90},{87,96,85},{63,78,89,100}};
scores[0]---->{78,80,90}
//二维数组的第一个一维数组的第一个元素
scores[0][0]
二维数组的遍历
int[][] scores = {{78,80,90},{87,96,85},{63,78,89,100}};
//二维数组的长度
int class1 = scores.length;
for (int i = 0; i <class1 ; i++) {
//一维数组的长度
int count = scores[i].length;
for (int j = 0; j <count ; j++) {
System.out.print(scores[i][j]+" ");
}
System.out.println();
}
}