Re: a question about alias of reference
www wrote:
Person tom = new Person("Tom");
Person tim = new Person("Tim");
List<Person> peopleList = new ArrayList<Person>();
peopleList.add(tom);
peopleList.add(tim);
for(Person p : peopleList)
{
if(p.getName().equalsIgnoreCase("Tom"))
{
p = null;
}
}
now, I expect the reference tom will be null, but it is not. Why? I
thought the reference p is just an alias of reference tom. Both are
pointing to the same object. Setting p to null equals to setting tom to
null.
No. Setting "p" to null equals setting "p" to null, only. The variable
"tom" is unchanged, as is the object to which it refers.
Note that the list in your example is unnecessary for the demonstration.
Your example is essentially equivalent to this:
Person tom1, tom2;
tom1 = new Person("Tom");
tom2 = tom1;
tom1 = null;
And again, assigning null to the variable affects only the variable, not
the object to which that variable referred, nor any other variable or
other memory location that may also refer to that object (such as "tom2").
Pete