File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Sorting array of objects by swapping references Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Sorting array of objects by swapping references" Watch "Sorting array of objects by swapping references" New topic
Author

Sorting array of objects by swapping references

Jignesh Gohel
Ranch Hand

Joined: Dec 28, 2004
Posts: 276
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.


Regards,
Jignesh

The Art Of Life Is To Know When To Be Useless And When To Be Useful - CHUANG TZU
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24184
    
  34

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?


[Jess in Action][AskingGoodQuestions]
Jignesh Gohel
Ranch Hand

Joined: Dec 28, 2004
Posts: 276
Thanks Ernest.Got your point.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Sorting array of objects by swapping references