When you pass in a list to Collections.sort(), it sorts your list and points your variable to that sorted list. I don't understand exactly how it works. In other words, how is it that the sort method is void? I would expect to have to do list = Collections.sort(list);.
But I thought that methods used a copy of whatever was passed in and that if changes are made to the object in the method, no changes are made to the original object. So my assumption is false, I take it?
Joel Christophel wrote:In other words, how is it that the sort method is void? I would expect to have to do list = Collections.sort(list);.
I think Jeanne's basically explained it to you, but you know what? I totally agree with you. I wish there was a version that also returned the List for you (sortAndReturn?). Indeed, I've written one for myself.
I also tend to write my setters that way too (ie, return a copy of the object that contains the method). Guess I just don't like void methods very much.
There's another possible justification (which you may or may not agree with). Returning void makes it clear that the sort() method has side-effects (since a void method that doesn't is pointless) - so it should be clear that it sorts the list that you passed in. If it returned the list, that might suggest that it's returning a new sorted list, leaving the old one alone.