mark mark - 29 days ago 8
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){

cmnt.setUser(commentUser.getLogin());
cmnt.setCreatedAtString(cmnt.getCreatedAt().format(DateTimeFormatter.ofPattern(Constants.DATE_TIME_FORMAT)));
}


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
cmnt
, the comments from
task.getcomments
changes.

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:

repository.save(task);


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

task.getComments();


return changed data? I did not save to database?

SQB SQB
Answer

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.