数组定义的三种不同形式以及数组存储对象动态赋值与静态赋值

1、数组定义
数组如同一所学生公寓,用来分别住男生女生的一种容器,数组只能是同一类型,当然java数组也能存储对象!!!
2、数组特点
数组拥有固定的索引顺序,并且从0开始
3、数组的格式
格式1:
元素类型[] 数组名 = new 元素类型[元素个数或数组长度];
示例:int[] arr = new int[5];

格式2:
元素类型[] 数组名 = new 元素类型[]{元素,元素,……};
示例:int[] arr = new int[]{3,5,1,7};
格式3:
元素类型[] 数组名 = {元素,元素,……};
示例:int[] arr = {3,5,1,7};
4、数组存储对象动态赋值与静态赋值

//定义一个NameSystem类
class NameSystem{
	private String name;
	private int times;
//定义有参构造器
	public NameSystem(String name,int times){
		this.setName(name);
		this.setTimes(times);
//以下是getset操作
		public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getTimes() {
		return times;
	}
	public void setTimes(int times) {
		this.times = times;
	}
	}
}

下面是在Main方法中的操作

  //1、创建对象
     NameSystem[] persons=new NameSystem[5];
//      persons[0].setName("张三"); 
//      persons[0].setTimes(0);
 //2、动态赋值
      persons[0]=new NameSystem("小李",0);
      persons[1]=new NameSystem("小张",0);
      persons[2]=new NameSystem("小王",0);
      persons[3]=new NameSystem("小明",0);
      persons[4]=new NameSystem("小刚",0);
     
  //1+2 == 3、静态赋值   
//      NameSystem[] persons={new NameSystem("小李",0),new NameSystem("小张",0),new NameSystem("小王",0),
//                            new NameSystem("小明",0),new NameSystem("小刚",0)
//                           };

分析:
数组存储对象时创建对象:实质是使用了格式1

数组存储对象动态赋值:实质是使用了格式2
数组存储对象静态赋值:实质是使用了格式3

5、数组内存分析
关键字new 会在堆内存中开辟相应的空间,分别赋予了两个数组不同的地址。当比较的时候,比较的是两个数组的地址

int[] in=new int[]{1,2,3};
	int[] in2=new int[]{1,2,3};
	System.out.println("in.equals(in2):"+in.equals(in2));
结果:
in.equals(in2):false

分析:
关键字new 会在堆内存中开辟相应的空间,分别赋予了两个数组不同的地址,所以为false

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

宜春

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

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

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

打赏作者

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

抵扣说明:

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

余额充值