• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sorting array of objects by swapping references

 
Jignesh Gohel
Ranch Hand
Posts: 276
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
These are my code snippets :

Model class:


Sorting by swapping actual values :


Output :
Element 0 ---> Person {id :1}
Element 1 ---> Person {id :2}
Element 2 ---> Person {id :3}

Sorting by swapping references :


Output :
Element 0 ---> Person {id :2}
Element 1 ---> Person {id :3}
Element 2 ---> Person {id :1}


I am unable to understand why the array didn't got sorted correctly when swapped the references.
If anybody can explain me the mechanism behind why the references swapping didn't worked, i would be thankful to him.

Thanks.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm unable to explain why you think the array should have been sorted by doing this, but maybe we can both help each other.

I think that perhaps you have some experience in the C/C++ language, where variables can contain either an object, or a reference to an object, and the same with arrays. By swapping array elements in C++, you're often physically copying objects around.

Note that in Java, you can never deal with to an "actual object;" all you ever have is a reference to an object. An array element is always a reference to an object, just as a local variable is.

So all Java variables of object type are basically C "dumb pointers." Assigning to a Java variable never changes anything except the value of the variable you actually assign to.

So in your first example, you assign to array elements, and so those array elements change.

But in your second example, you assign to a bunch of local variables, and so only the local variables change; the array is completely untouched.

Does it make sense now?
 
Jignesh Gohel
Ranch Hand
Posts: 276
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ernest.Got your point.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic