| Author |
List Assignment vs. List.addAll()
|
Tom Henricksen
Ranch Hand
Joined: Mar 23, 2004
Posts: 135
|
|
What is the difference between these two methods of getting a list. And this code. Is there any difference in these. I ask as I tried the first approach with problems. When I tried the second it worked. Thanks, Tom
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24057
|
|
The list you create with "new" in the first version is simply discarded when you make the assignment. Assigning to a Java variable in Java always completely discards any existing value without affecting it in any way. In this first version, you end up with localList pointing to the exact same List that object.getAList() returned -- meaning that if "object" still has a reference to that List, code in "object" could modify that list, and the changed would be visible via localList, and vice-versa, because they reference the same object. In the second version, the elements of "object"'s list are put into a new list. Now either object can chnage their own list independently, without affecting the other one.
|
[Jess in Action][AskingGoodQuestions]
|
 |
Ilja Preuss
author
Sheriff
Joined: Jul 11, 2001
Posts: 14112
|
|
The difference in pictures:
|
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
|
 |
 |
|
|
subject: List Assignment vs. List.addAll()
|
|
|