mark mark - 1 year ago 111
Java Question

Manipulating moved arrays change main array data in java

I take like this:

Collection<TaskComment> commentsCollection = task.getComments();
ArrayList<TaskComment> comments = new ArrayList<>(commentsCollection);

for(TaskComment cmnt : comments){


Here I take comments and put them into a collection, then into an arraylist. Then I manipulate the comments with DTO class methods.

But when I change
, the comments from

I think this code is enough but I can give more code if you want. Why does it change? It was supposed not to change because I moved it to collection then to array?

I don't do this:;

after I manipulate the comment, so it must not save to database? So why does


return changed data? I did not save to database?

Answer Source

It's because you're still looking at the same TaskComment objects.

References to a specific comment may be in two collections, commentsCollection and comments, but it's only one object. It doesn't matter how you get at the object, if you manipulate it, it changes.

Imagine your objects, in this case comments, as boxes. You tie a red string to each box and give the strings to Alice to hold. Then you tie a blue string to each box and give those strings to Bob to hold.
Now let's say Bob pulls on a string and gets a box. He opens the box, puts a marble in it and shoves the box back in its place.
Now Alice pulls on the string for that box and gets the box. If she opens it, she'll find a marble in it.

What happens if you call task.getComments(); again, depends on the implementation. If you didn't save to the database and if that method gets them from the database each and every time, you shouldn't see any changes in those comments. It's as if you get a new set of boxes for Alice.

However, what's far more likely is that when you load a Task from the database, it loads the associated comments with it, adding them as a property of the Task. Then, with each call to get the comments, you don't get them from the database, you get them from the Task object. And those comments are the one both Alice and Bob have strings tied to.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download