您的位置:首页 > 其它

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

2019-04-18 11:50 176 查看

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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐