引用类型数组

声明基本类型数组和引用类型数组

int          [ ]  arr;  //基本类型数组
double   [ ]  ds;   //基本类型数组

Student [ ]   stus; //引用类型数组
Airplane[ ]   as;   //引用类型数组
Bee       [ ]   bs;   //引用类型数组


举例

//声明int型数组arr,包含3个元素,每个元素都是int类型,默认值为0
int[] arr = new int[3];

//声明Student型数组stus,包含10个元素,每个元素都是Student类型,默认值为null
Student[] stus = new Student[10];

//声明Airplane型数组as,包含5个元素,每个元素都是Airplane类型,默认值为null
Airplane[] as = new Airplane[5];

//声明Bee型数组bs,包含20个元素,每个元素都是Bee类型,默认值为null
Bee[] bs = new Bee[20];

 给基本类型数组和引用类型数组赋值举例

只要是引用类型,就需要new,因为引用类型数组是引用,所以给引用类型数组赋值,也需要new

int[] arr = new int[3];
arr[0] = 100;

Student[] stus = new Student[3]; //创建Student数组对象
stus[0] = new Student("zs",25,"LF"); //创建Student对象
stus[1] = new Student("ls",26,"JMS");
stus[2] = new Student("ww",24,"SD");

引用类型数组的演示
第一步:创建学生类 

//学生类
public class Student {
	String name;
	int age;
	String address;
	
	Student(String name,int age,String address){
		this.name = name;
		this.age = age;
		this.address = address;
	}
	
	void study() {
		System.out.println(name+"在学习...");
	}
	void sayHi() {
		System.out.println("大家好,我叫"+name+",今年"+age+"岁了,家住"+address);
	}
}

 第二步:创建引用类型数组

引用类型数组能点出来什么,要看引用的类型

public class RefArrayDemo {
	public static void main(String[] args) {
		Student[] stus = new Student[3];
		stus[0] = new Student("zhangsan",25,"LF");
		stus[1] = new Student("lisi",26,"JMS");
		stus[2] = new Student("wangwu",27,"SD");
        /*下面这一句话的效果和上面四句话是一样的
          Student[] ss = new Student[]{
	      new Student("zhangsan",25,"LF"),
	      new Student("lisi",26,"JMS"),
	      new Student("wangwu",27,"SD")
	    };
        */
		System.out.println(stus[0].name); //输出第1个学生的名字
		stus[1].age = 24; //给第2个学生的年龄赋值为24
		stus[2].sayHi(); //第3个学生跟大家问好
		for(int i=0;i<stus.length;i++) { //遍历所有学生
			System.out.println(stus[i].name); //输出每个学生的名字
			stus[i].sayHi(); //每个学生跟大家问好
		}
	}
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

謹言

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

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

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

打赏作者

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

抵扣说明:

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

余额充值