java中的数组

数组属于引用数据类型。

数组中可以存储基本数据类型,也可以存储引用数据类型的数据。

数组因为是引用类型。所以数组对象在堆内存中。

数组当中如果存储的是java对象的话,实际上存储的是对象的引用(内存地址),数组中不能直接存储java对象。

数组一旦创建,在java中规定,长度不可变。

所有的数组对象都有length属性,用来获取数组中元素的个数。

java中的数组要求数组中元素的类型统一。比如int类型的数组只能存储int类型。

数组中的存储的每一个元素都是连续的。

数组中首元素的内存地址作为整个数组对象的内存地址。

数组下标从0开始到length-1

数组的优点:

  每一个元素的内存地址在空间存储上是连续的。

  每一个元素类型相同,所占空间大小一样。

  知道第一个内存地址,又知道每一个元素占用空间的大小,又知道下标,可以通过数学表达式就能算出某个下标上元素的内存地址,直接通过内存地址定位元素。所以效率高。

数组的缺点:

  数据的增加和删除都会导致数据的前移和后移。

  数组中无法存储大数据量,因为很难在内存空间中找到一块很大的连续的内存空间。

******************

在数组中,对于最后一个元素的增删,是没有效率影响的。

数组的两种定义方法:静态初始化和动态初始化。

  int[] array1 = {1, 3, 4, 5};(静态初始化)

  int[] array2 = new int[5];(动态初始化,初始化一个长度为5的int类型数组,每个元素的默认值为0)

  array2[i]=x;

package com.lut.javase.array;

/*
当数组中存储的数据类型为:引用数据类型的时候
对于数组来说,实际只能存储java对象的“内存地址”,数组中存储的每个元素是“引用”;
* */

public class arrayTest03 {
    public static void main(String[] args) {
        Animal a = new Animal();
        Animal b = new Bird();
        Animal c = new Cat();
        Animal[] animals = {a, b, c, new Animal(), new Cat(), new Bird()};
//        for(int i=0; i < animals.length; i++){
//            animals[i].move();
//        }
        for(int i = 0; i < animals.length; i++){
            if(animals[i] instanceof Bird){
                Bird x = (Bird)animals[i];
                x.sing();
            }else if(animals[i] instanceof Cat){
                Cat y = (Cat)animals[i];
                y.catchMouse();
            }
        }
    }
}

class Animal{
    public void move(){
        System.out.println("The animal is moving");
    }
}
class Cat extends Animal{
    public void move(){
        System.out.println("The cat is walking");
    }
    public void catchMouse(){
        System.out.println("The cat is catching to mouse");
    }
}
class Bird extends Animal{
    public void move(){
        System.out.println("The bird is flying");
    }
    public void sing(){
        System.out.println("The bird is singing");
    }
}

 

posted @ 2022-06-29 15:56  _八级大狂风  阅读(68)  评论(0编辑  收藏  举报