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
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: 24199

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:
subject: List Assignment vs. List.addAll()
jQuery in Action, 3rd edition