Java_基础—对象数组的概述和使用

新建一个学生类,属性为name,age

Alt + Shift +S → C 空参构造
Alt + Shift +S → O 有参构造
Alt + Shift +S → R 生成set和get 方法

package com.soar.bean;

public class Student {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Student(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public Student() {
        super();    
    }

    }
}

创建一个Array类

package com.soar.collection;

import com.soar.bean.Student;

public class Demo1_Array {
/*
        * * A:案例演示
        * 需求:我有5个学生,请把这个5个学生的信息存储到数组中,并遍历数组,获取得到每一个学生信息。
        Student[] arr = new Student[5];                 //存储学生对象
        arr[0] = new Student("张三", 23);
        arr[1] = new Student("李四", 24);
        arr[2] = new Student("王五", 25);

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

        * B:画图演示
            * 把学生数组的案例画图讲解
            * 数组和集合存储引用数据类型,存的都是地址值
 */
    public static void main(String[] args) {
        // int[] arr = new int[5];          //创建基本数据类型数组
        Student[] arr = new Student[5];     //创建引用数据类型数组
        arr[0] = new Student("张三",23);      //创建了一个学生对象,存储在数组的第一个位置
        arr[1] = new Student("李四",25);      //创建了一个学生对象,存储在数组的第二个位置
        arr[2] = new Student("王五",18);      //创建了一个学生对象,存储在数组的第三个位置

        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);     //默认调用Object类的toString方法
        /*
         * 输出结果:
          com.soar.bean.Student@b9e45a
          com.soar.bean.Student@3ef810
          com.soar.bean.Student@100363
          null
          null
        */
        }
    }

}

Array类中Student对象在创建时的内存示意图

① Demo1_Array.class 加载到内存
② Main方法 进栈
③ 发现Student类,Student.class 加载到内存
④ 在main 中Student[] arr = new Student[5]; 存储的都是对象地址值,通过地址值访问对象
⑤ Arr[0] = new Student(“张三”,23) 在堆中生成对象存储空间

 

posted @ 2017-07-13 08:53  Soar_Sir  阅读(214)  评论(0编辑  收藏  举报