Luke Taylor
Luke Taylor

Reputation: 9599

List<> object change after making a copy

I've got the following code, where I create a List<> object called users. I set the users object to a different List<>. Yet as soon as I add something to the users object, the other List<> object also changes in size? What is this sorcery? Is this supposed to be like so, I thought I'm only making a copy of the other List<> object.

When I run this code, this log displays: Amount of friends: 0 Amount of friends: 1 Amount of friends: 1

users = new ArrayList<Profile>(); // Friends of this player
        users = game.getUserProfile().getProfileFriends();
        game.getGameLog().d(classTAG, "Amount of Friends: " + game.getUserProfile().getProfileFriends().size());
        users.add(game.getUserProfile());
        game.getGameLog().d(classTAG, "Amount of Friends: " + game.getUserProfile().getProfileFriends().size());
        this.sortUsersAccordingToXP();
        game.getGameLog().d(classTAG, "Amount of Friends: " + game.getUserProfile().getProfileFriends().size());

Note: This is not all the code, yet the code influences my question, as soon as I remove the add method, the other List<> doesn't grow in size (and of course the users object as well).

Upvotes: 2

Views: 495

Answers (3)

John
John

Reputation: 2425

In Java you're dealing with references to objects, not the actual object itself.

users = game.getUserProfile().getProfileFriends();

That line isn't copying the contents from the original list into users, it's making the users variable point to the same list as game.getUserProfile().getProfileFriends(). So now users and game.getUserProfile().getProfileFriends() both reference to the same list in memory, so you don't have two separate lists as you think.

Think of how inefficient and expensive things would get if Java literally assigned and passed around entire objects all the time.

To copy the contents of the current list into a new one, you simply use the constructor that takes a Collection and copies its items into the new list:

users = new ArrayList<Profile>(game.getUserProfile().getProfileFriends()); 

Upvotes: 2

Akhi
Akhi

Reputation: 2242

IN your

`users = game.getUserProfile().getProfileFriends();`

the users and the game field are havin same reference by doing a simple copy. Hence changes are reflected in each other.

Upvotes: 0

Marc-Christian Schulze
Marc-Christian Schulze

Reputation: 3254

users = game.getUserProfile().getProfileFriends();
Copies the reference to the list - not the list!
Use the Constructor of ArrayList to create a shallow copy.

Upvotes: 6

Related Questions