集合基础--对象数组

1.题目

需求:将(张三,23)(李四,24)(王五,25)封装为3个学生对象并存入数组
随后遍历数组,将学生信息输出在控制台

2.思路

1.定义学生类准备用于封装数据
2.动态初始化长度为3的数组,类型为Student类型
3.根据需求创建3个学生对象
4.将学生对象存入数组
5.遍历数组,取出每一个学生对象
6.调用对象的getxxx方法获取学生信息,并输出在控制台

3.代码

错误代码 展示

import domain.Student;

public class 对象数组 {
//    思路:
//    1.定义学生类准备用于封装数据
//    2.动态初始化长度为3的数组,类型为Student类型
//    3.根据需求创建3个学生对象
//    4.将学生对象存入数组
//    5.遍历数组,取出每一个学生对象
//    6.调用对象的getxxx方法获取学生信息,并输出在控制台
    public static void main(String[] args) {
        //2.动态初始化长度为3的数组,类型为Student类型
        Student[] arr=new Student[3];
        //3.根据需求创建3个学生对象
        Student stu1=new Student("张三",23);
        Student stu2=new Student("李四",24);
        Student stu3=new Student("王五",25);
        //4.将学生对象存入数组
        arr[0]=stu1;
        arr[1]=stu2;
        arr[2]=stu3;
        //5.遍历数组,取出每一个学生对象
//        for (int i = 0; i < arr.length; i++) {
//            Student temp=arr[i];
//            System.out.println(temp.getName()+"..."+temp.getAge());
//        }
        for (int i = 0; i < arr.length; i++){
            System.out.println(arr[i]);
        }
    }
}

错误点出现在 最后的for循环处,直接打印 得到的是存储的地址:

正确代码

import domain.Student;

public class 对象数组 {
//    思路:
//    1.定义学生类准备用于封装数据
//    2.动态初始化长度为3的数组,类型为Student类型
//    3.根据需求创建3个学生对象
//    4.将学生对象存入数组
//    5.遍历数组,取出每一个学生对象
//    6.调用对象的getxxx方法获取学生信息,并输出在控制台
    public static void main(String[] args) {
        //2.动态初始化长度为3的数组,类型为Student类型
        Student[] arr=new Student[3];
        //3.根据需求创建3个学生对象
        Student stu1=new Student("张三",23);
        Student stu2=new Student("李四",24);
        Student stu3=new Student("王五",25);
        //4.将学生对象存入数组
        arr[0]=stu1;
        arr[1]=stu2;
        arr[2]=stu3;
        //5.遍历数组,取出每一个学生对象
        for (int i = 0; i < arr.length; i++) {
            Student temp=arr[i];
            System.out.println(temp.getName()+"..."+temp.getAge());
        }
//h
    }
}

定义一个Student类型的变量temp来存储数组数据

4.注意点:

新建一个domain包,包下新建Student类用于封装数据

package domain;

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

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

    public Student() {
    }

    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;
    }
}

定义好 name和age后,右键“生成”

以上操作可以生成构造函数、get()方法、set方法

5.缺点

当有新的信息想要插入,该对象数组是容量不够的。只能新建容量更大的数组才能让新的信息插入。

  • 11
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值