集合基础--对象数组

1.题目

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

2.思路

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

3.代码

错误代码 展示

java 复制代码
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循环处,直接打印 得到的是存储的地址:

正确代码

java 复制代码
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类用于封装数据

java 复制代码
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.缺点

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

相关推荐
水蓝烟雨13 分钟前
[面试精选] 0094. 二叉树的中序遍历
算法·面试精选
超闻逸事20 分钟前
【题解】[UTPC2024] C.Card Deck
c++·算法
暴力求解31 分钟前
C++类和对象(上)
开发语言·c++·算法
JKHaaa38 分钟前
几种简单的排序算法(C语言)
c语言·算法·排序算法
让我们一起加油好吗44 分钟前
【基础算法】枚举(普通枚举、二进制枚举)
开发语言·c++·算法·二进制·枚举·位运算
FogLetter1 小时前
微信红包算法揭秘:从随机性到产品思维的完美结合
算法
YGGP1 小时前
吃透 Golang 基础:数据结构之 Map
开发语言·数据结构·golang
BUG收容所所长1 小时前
二分查找的「左右为难」:如何优雅地找到数组中元素的首尾位置
前端·javascript·算法
weixin_419658312 小时前
数据结构之栈
数据结构
图先2 小时前
数据结构第一章
数据结构