wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes List Assignment vs.  List.addAll() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "List Assignment vs.  List.addAll()" Watch "List Assignment vs.  List.addAll()" New topic

List Assignment vs. List.addAll()

Tom Henricksen
Ranch Hand

Joined: Mar 23, 2004
Posts: 136

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.

Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24183

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

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://aspose.com/file-tools
subject: List Assignment vs. List.addAll()
Similar Threads
Reusabilty of code lack in using interfaces for polymorphism
Polymorphic Declaration
Question about example in Hanumant's book
What the use and benefit of writing also tell me the difference
is it all about performance (Arraylist) ?