JAVA中的数组对象

代码:Student [] sd=new Student[5];//新建一个学生类的数组对象sd。
        sd[0]=new Student("kj",13);//为数组对象赋值。
        sd[1]=new Student("zj",14);
        sd[2]=new Student("gj",15);
        sd[3]=new Student("mj",16);

//遍历这个数组对象。

    for(int i=0;i<sd.length;i++){
            
            System.out.println(sd[i]);
            
        }

运行结果:

com.yakir.collect.Student@6bbc4459
com.yakir.collect.Student@152b6651
com.yakir.collect.Student@544a5ab2
com.yakir.collect.Student@5d888759
null

需要注意的是,打印出来的结果是调用的是obect类的toString方法。如果想要看到Student类中的赋值后的结果,就需要对Student类重写toString方法。

代码:public String toString() {
        return "Student [name=" + name + ", age=" + age + "]";
    }
   

运行结果:

Student [name=kj, age=13]
Student [name=zj, age=14]
Student [name=gj, age=15]
Student [name=mj, age=16]
null
首 先理解一下这个过程。实现类加载进内存,主方法进栈(也就是main方法),Student类加载内存,之后通过Student类建立数组,数组在堆中创 建连续的空间,为5块(大小为自己设定大小),索引为0开头,依次加一,默认触发值为null(数组中没有元素返回为null)。每个索引,都对应的一个 地址值。也就是说,数组对象中的数组并不存储对象,而是存储了记录对象的地址值,通过地址值找到类实体。

原文地址:https://www.cnblogs.com/lovelyYakir/p/5561405.html