java进阶(9)--数组

1、基本概念:
一、数字为引用数据类型
二、数组其实是一个容器,能够同时容纳多个元素
三、数组可存储基本数据类型,也能够存储引用数据类型的数据
四、数组一旦建立、长度不可变、且数组中元素类型必须统一
五、数组能够经过Length获取长度
六、数组中每一个元素都有下标,0开始,以1递增,最后一个元素下标:Length-1
七、数组优势:查询某个下标的元素时候效率较高
八、数组缺点:数组增删元素效率比较低,没法存储大数据量
 
2、数组语法:
一、数组类型,以及动态初始化时默认值
int[] array1          --0
double[]array      --0.0
boolean[]array3  --false
String[]array4     --null
Object[]array5    --null(引用类型)
short[]array6      --0
long[]array7       --0.0L
float[]array8       --0.0F
char[]array9       --\u000
二、初始化
静态初始化:
int[]array1=new int[]{100,200,300};
动态初始化:默认值0
int[]array1=new int[5];
三、(反向)遍历一维数组
 
3、方法的参数为数组
一、参考示例
二、再说main方法,传递参数
Idea-run-editconfig-设置传递参数
 
4、数组存储为引用数据类型(结合多态实现)
package cnblogs;
public class TestAdvance09array4 {
    public static void main(String[] args) {
        Cat a1=new Cat();
        Bird a2=new Bird();
        Animal[] animals={a1,a2};
        for(int i=0;i<animals.length;i++){
            //调用公有的方法
            animals[i].move();
            //特有方法须要向下转型
            if( animals[i] instanceof Cat) {
                Cat cat=(Cat)animals[i];
                cat.catchMouse();
            }
            else if( animals[i] instanceof Bird){
                Bird bird=(Bird)animals[i];
                bird.sing();
            }
        }
        }
}
 
class Animal{
    public void move(){
        System.out.println("Animal move...");
    }
}
 
class Cat extends Animal{
    public void move() {
        System.out.println("猫在走猫步...");
    }
    public void catchMouse(){
        System.out.println("猫捉老鼠...");
    }
}
 
class Bird extends Animal{
    public void move() {
        System.out.println("鸟在飞翔...");
    }
    public void sing(){
        System.out.println("鸟在唱歌...");
    }
}
查询运行结果:
 
5、数组扩容(效率较低,因涉及到全量的拷贝)
一、arraycopy()方法,4个参数:
(1)源数组(2)起始下标(3)目标数组(4)起始下标(5)长度
二、示例代码
 
6、二维数组
一、二维数组的遍历
二、二维数组的入参传递
相关文章
相关标签/搜索