• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Sorting array of objects by swapping references

 
Ranch Hand
Posts: 276
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Ernest.Got your point.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic