The moose likes Beginning Java and the fly likes List Assignment vs.  List.addAll() Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "List Assignment vs.  List.addAll()" Watch "List Assignment vs.  List.addAll()" New topic
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
    
  13

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
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: List Assignment vs. List.addAll()
 
Similar Threads
What the use and benefit of writing also tell me the difference
is it all about performance (Arraylist) ?
Polymorphic Declaration
Reusabilty of code lack in using interfaces for polymorphism
Question about example in Hanumant's book