先上两个例子例子1:public class IntegerArray{
public static void main(String[] args){
Integer[] scores1 = new Integer[]{1,2,3,4,5};
Integer[] scores2 = new Integer[scores1.length];
for(int i = 0; i < scores1.length; i++){
scores2[i] = scores1[i];
}
for(Integer score2: scores2){
System.out.print(score2);
}
System.out.println();
scores2[0] = 7;
for(Integer score1 : scores1){
System.out.print(score1);
}
System.out.println();
for(Integer score2: scores2){
System.out.print(score2);
}
}
}
--------------------------------------------------------
运行结果:
12345
12345
72345
--------------------------------------------------------
例子2:
public class ClassArray {
public static void main(String[] args){
Clothes[] c1 = {new Clothes("red", 'L'), new Clothes("blue", 'M')};
Clothes[] c2 = new Clothes[c1.length];
for(int i = 0; i < c1.length; i++){
c2[i] = c1[i];
}
for(Clothes c : c2){
System.out.print(c.color + "--" + c.size +" ");
}
c2[0].color = "black";
System.out.println();
for(Clothes c : c1){
System.out.print(c.color + "--" + c.size + " ");
}
System.out.println();
for(Clothes c : c2){
System.out.print(c.color + "--" + c.size +" ");
}
}
}
----------------------------------------------------------------------
运行结果:
red--L blue--M
black--L blue--M
black--L blue--M
----------------------------------------------------------------------
疑问:同样是类类型数组,为什么运行的结果不同,一个是2个数组变量分别指向2个不同的数组对象,
另一个则是2个数组变量指向同一个数组对象;难道就是因为Integer这个类比较特殊?希望知道的人帮忙解答一下。。。
4 回答
Corbie亚东
TA贡献53条经验 获得超25个赞
Integer时候他们传的是个值 而到自定义时候他们传的是一个个对象 当你去修改 自定义对象时会去堆中修改指定地址的对象值 c2[i] = c1[i]; 给的是指定的对象地址 貌似是这样的 你再去查查资料
慕工程5894045
TA贡献2条经验 获得超0个赞
楼上说的很对自定义对象传的是对象的引用的副本,但是指向的是同一个对象,所以改变指向的内容的话,就会改变你指定对象的值,你最初的对象的引用是不会变化的,但是这里Integer为什么当成基本数据类型处理,而不是也当成对象的引用,这点我还不是很明白。
这老头坏的很_2019
TA贡献1条经验 获得超0个赞
例子2里的类是自己定义的,代码如下:
class Clothes{
String color;
char size;
Clothes(String color, char size){
this.color = color;
this.size = size;
}
}
添加回答
举报
0/150
提交
取消