Often in Java one ends up using ArrayLists to store objects.
This is a somewhat tricky operation that gets forgotten too often, therefore I'm documenting it for future reference to myself. Much of what is written here was based on the tutorial from Mkyong: http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/
Make the object that you want to order to extend the "Comparable" class.
On my case, I want to apply the ordering on the SourceCodeObject class, so I add the line:
And it looks like this:
Override the "compareTo" method. On this case the comparison can occur between any two attributes of the objects that you are comparing. I find it difficult to understand in detail how it works. For my case it was enough to subtract two values and return the value. You find the code example at:
Convert the ArrayList to an array and then sort the array. This is the part that I find tricky because the syntax to convert the ArrayList to a plain array is not straightforward to understand, even from the help menu.
It should be something like:
SourceCodeFile array = myArrayList.toArray(new SourceCodeFile[myArrayList.size()]);
You find the code example at:
That's it. Enjoy the sorted array!
- Add the "Comparable" class to the object you want to compare
- Add the "toCompare" method
- Apply the Arrays.sort for ordering the items on a new array.
This method worked for me and I found it ok. Surely other ways exist. What do you think? How would you have implemented ordering?