Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

I don't get the findAll and then append thing.

Java -> Intro to Java Web Development with Spark -> Bells and Whistles -> Building Our Model Starting at 5:35

He says: "In case somebody tries to get cheecky and does a findAll() and then appends the list" What is that supposed to mean? I understand that you can make a copy of that list because collections can take another collections and create a brand new copy. I also know that append means to add something to a list - but I don't understand what he means when he says "do a findAll() and then do your own appending..."

Thanks in advance!

2 Answers

What he means is, we are not going to return the list itself which he have as a member variable in the class. We aren't doing that because in that case, the caller of the method will get the list, and can do whatever he wants with it and those changes will be reflected in our member variable. So we don't want that, which is why we are making an exact copy of the list we have and hand that over as a return value, so if additional changes are done to that particular list we returned, they won't be reflected in our "original" list so to speak.

An analogy would be, you ask for a list of teacher names at a university and the local admin hands you a list on paper. Now, imagine if whenever you add a name to that paper, or strike out a name, the original list the admin has is also updated with the changes you make at home, which isn't good. Instead, the admin should give you a list on paper which doesn't have this "connection" to the original list, so whatever you do to the list, isn't reflected in the original.

It's all because in Java what we are returning is a reference to the object and the reference we return shouldn't point to our original member variable object. So in order to not keep this "connection" alive, we are creating a new object with the exact same contents as the original one and hand a reference to that copied object over and don't worry what happens with it.

Hope it makes more sense now :).

Yes, it totally makes sense. I cannot believe I didn't figure out by myself something that's so easy and common sense - probably because I was tired.

Thank you very much for taking the time to provide this complex answer!

Cheers!

You are most welcome, glad I could help.