【code=Java】
class Person{
private int i;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public Person(int i){
this.i=i;
}
}
public class J2SESample { public static void main(String[] args) {
Person p1=new Person(1);
Person p2=new Person(2);
Person[] ps=new Person[2];
ps[0]=p1;
ps[1]=p2;
p1=null;//here
System.out.println(ps[0].getI());
}
}
【/code】
问题: 在p1置为null后,ps[0]同时为null么?ps[0].getI()返回什么?
class Person{
private int i;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public Person(int i){
this.i=i;
}
}
public class J2SESample { public static void main(String[] args) {
Person p1=new Person(1);
Person p2=new Person(2);
Person[] ps=new Person[2];
ps[0]=p1;
ps[1]=p2;
p1=null;//here
System.out.println(ps[0].getI());
}
}
【/code】
问题: 在p1置为null后,ps[0]同时为null么?ps[0].getI()返回什么?
将p1置为null,对ps[0]没有影响,它还是指向new Person(1)
是否可以这样理解,置为null只是取消掉了p1对那块区域的链接?
p1=null 只是p1这个对象为空,地址还是存在。返回的值为1
ps[0].getI()返回1
ps[0] 和p1是指向和同一块区域.
p1设为null,意思是让p1谁也不指向了,但ps[0]没有变,还指向原来的地方.