• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why arrayLIst does not sort the elements i add

 
Meir Yan
Ranch Hand
Posts: 599
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48382
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48382
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic