• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

why arrayLIst does not sort the elements i add

 
Ranch Hand
Posts: 620
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ?
 
Marshal
Posts: 79239
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Marshal
Posts: 79239
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic