• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Ordered and Sorted

 
gaurav singhal
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can somebody explain howz order is defined? How to find which collection is ordered or unordered/sorted or unsorted?
 
Nikhil Goel
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ordering & Sorting are 2 distinct names to same concept . Java has the concept of Natural Ordering means objects like Strings are self ordered in java .
Hence collections that contain string as key or string as objects are by default sorted .

Collections like List,Set ,Map need sorting . There are variants to these also like SortedSet , TreeSet etc .
ArrayList,HashMap,Hashtables need sorting...

If you want your objects to be sorted you have to implement a Comparator interface for that . It has a method compareTo(Object 1 , Object2) that sorts 2 objects while adding them in Collections.

There is also a utility method sort(Collection collection) on Collections class that sorts the collection .
 
Marcus Green
arch rival
Rancher
Posts: 2813
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that something that is ordered may not be sorted. Ordering means that the order of access is defined, e.g. I get stuff back in the order that I put it in. It may not however be sorted in any way.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic