wood burning stoves 2.0*
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 Murach's Java Servlets and JSP this week in the Servlets 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: 37953
    
  22
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: 37953
    
  22
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.
 
Consider Paul's rocket mass heater.
 
subject: why arrayLIst does not sort the elements i add
 
Similar Threads
questions on Generic
Adding to Treeset
Regarding sorting elements in ArrayList
Collection VS ArrayList.
Linked List - inserting value to correct position