• Post Reply Bookmark Topic Watch Topic
  • New Topic

Collections.sort method and pass by value  RSS feed

 
raja singh kumar
Ranch Hand
Posts: 189
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Suppose a collection(say ArrayList) is passed as a parameter to the Collections.sort() method. As we know, java is pass by value for primitives as well as objects, so the modifications made to the ArrayList should not reflect in the calling method, but when we see the list in the calling method  it is sorted. Is this not in conflict with pass by value concept?
 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java is pass by value for primitives and references. There is no direct way to pass objects around. When you pass a list to the sort method, you actually pass a reference to that list, by value.
 
Campbell Ritchie
Marshal
Posts: 56581
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are conflating pass by value and immutable objects. What you are passing is a value of the reference of the List's location. Once you have that location, you can access the List and change its state. You can add elements, you can remove elements, you can sort it, you can empty it, or anything. But it remains the same List in the same memory location.

Imagine you have an address list on paper, made by putting pages into a
lever arch file. Now you give it to a friend who asked, “Have you got Satish's address?” first writing, “Raja's address list,” on it. The next day the friend returns your address list saying thank you and when you look at it, it seems to be different. It is still the same address list because it still has, “Raja's address list,” written on. So you ask, and the friend says, “I have sorted al the pages in alphabetical order.” That is a real‑life analogy of what you have done with the sort method. The friend might have added pages thinking you needed additional addresses or removed pages because whoever is on the pages is no longer at that address. Or written corrections on pages.

By the way: In Java8 Lists were given a sort() method; that may be neater than using Collections.sort.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!