Re: a question about alias of reference
On 07/16/2010 09:47 PM, 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.
Thank you very much.
Others have answered (correctly of course), but here's yet another way
of saying it.
The "for each" loop
for (Person p : peopleList) {}
In this version of the loop, you don't have any means of changing the
contents of a list (you can mutate objects "contained" in the list, but
not the list itself), other than calling peopleList.set() (or remove(),
etc.) methods. For that you also need an index.
The "for each" loop (i believe it was introduced in Java SE 5.0) is
nothing but a shortcut of saying something like:
for (ListIterator<Person> i = peopleList.listIterator();
i.hasNext(); ) {
Person p = i.next();
}
The p object will be exactly the same as in the previous "for each"
loop. In this version of the loop I believe it's much clearer to see why
the list won't change when you set p to null. However, here you have
some extras -- an instance of the ListIterator class. You can use it to
access the list, and you don't even need that p variable. It's quite
useless if you just want to set some list member to null.
So you would write something like:
boolean isEqualToTom = false;
for (ListIterator<Person> i = peopleList.listIterator();
i.hasNext();
isEqualToTom = i.next().getName().equalsIgnoreCase("Tom")) {
if (isEqualToTom) {
i.set(null);
}
}
Of course, this usually is not how you want to do it in real life (it's
quite messy). It's just an illustration of the list iterator. For Lists
you can make your own simple index iterator and just use "for each" loop
with set(int,Object) method of the List interface.