This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Soft Skills and have John Sonmez on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes why arrayLIst does not sort the elements i add Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "why arrayLIst does not sort the elements i add" Watch "why arrayLIst does not sort the elements i add" New topic
Author

why arrayLIst does not sort the elements i add

Meir Yan
Ranch Hand

Joined: Apr 27, 2006
Posts: 597
why does the array list does not sort the elements by the order i add them
how can i make it sort them by the order the elements added ?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40034
    
  28
By array list I presume you mean java.lang.ArrayList? It usually maintains its elements in the order they were added, assuming you add them in order.will add however many Foos and maintain them in order whereaswill get them all in reverse order. (As well as slower performance.)

They have not at this point been sorted. If you want to sort them, the elements must implement the Comparable interface, or you pass an object of the Comparator interface to the Collections.sort method.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40034
    
  28
To try to finish your query: sorting with Comparable sorts by the "natural order" and sorting with a Comparator sorts by whatever the Comparator thinks it is supposed to sort by. After sorting you will have lost the insertion order.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: why arrayLIst does not sort the elements i add