JAVA笔记- JAVA对象数组的遍历与使用详解

1- 对象数组概述

  1. 基本类型的数组:存储的元素为基本类型
    int[] arr={1,2,3,4}
  2. 对象数组:存储的元素为引用类型
    Student[] stus=new Student[3];
    解释::
    Student代表一个自定义类
    Stus数组中stus[0],stus[1],stus[2]的元素数据类型为Student,
    都可以指向一个Student对象

2- 对象数组案例

创建一个学生数组,存储三个学生对象并遍历

/*
 * 自动生成构造方法:
 * 		代码区域右键 -- Source -- Generate Constructors from Superclass...	无参构造方法
 * 		代码区域右键 -- Source -- Generate Constructor using Fields...		带参构造方法
 * 自动生成getXxx()/setXxx():
 * 		代码区域右键 -- Source -- Generate Getters and Setters...
 */
public class Student {
	private String name;
	private int age;
	
	public Student() {
		
	}

	public Student(String name, int age) {
		this.name = name;
		this.age = 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;
	}
	
	
}

package com.itheima;
/*
 * 创建一个学生数组,存储三个学生对象并遍历
 * 
 * 分析:
 * 		A:定义学生类
 * 		B:创建学生数组
 * 		C:创建学生对象
 * 		D:把学生对象作为元素赋值给学生数组
 * 		E:遍历学生数组
 */
public class StudentDemo {
	public static void main(String[] args) {
		//创建学生数组
		Student[] students = new Student[3];
		
		//创建学生对象
		Student s1 = new Student("曹操",40);
		Student s2 = new Student("刘备",35);
		Student s3 = new Student("孙权",30);
		
		//把学生对象作为元素赋值给学生数组
		students[0] = s1;
		students[1] = s2;
		students[2] = s3;
		
		//遍历学生数组
		for(int x=0; x<students.length; x++) {
			Student s = students[x];
			//System.out.println(s);
			System.out.println(s.getName()+"---"+s.getAge());
		}
	}
}

3- 对象数组的内存图解

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鬼刺

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值