集合基础--对象数组

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.缺点

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

相关推荐
我是苏苏1 小时前
C#高级:程序查询写法性能优化提升策略(附带Gzip算法示例)
开发语言·算法·c#
sali-tec2 小时前
C# 基于halcon的视觉工作流-章56-彩图转云图
人工智能·算法·计算机视觉·c#
黑岚樱梦6 小时前
代码随想录打卡day23:435.无重叠区间
算法
Kuo-Teng6 小时前
Leetcode438. 找到字符串中所有字母异位词
java·算法·leetcode
gihigo19987 小时前
MATLAB使用遗传算法解决车间资源分配动态调度问题
算法·matlab
墨染点香7 小时前
LeetCode 刷题【138. 随机链表的复制】
算法·leetcode·链表
却道天凉_好个秋7 小时前
目标检测算法与原理(一):迁移学习
算法·目标检测·迁移学习
兮山与8 小时前
算法24.0
算法
晓北斗NorSnow9 小时前
机器学习核心算法与学习资源解析
学习·算法·机器学习