Wednesday 3 April 2013

Difference between Ordered and Sorted in java Collection

Generally, we can use the words Ordered and Sorted interchangeably as sorted things can also be called in an ascending or descending order but while reading java collection you can wondered that these words are used differently like set interface is sorted by default in nature and list interface is ordered by default in nature. The difference between ordered and sorted in case of java collection can be understand as:
Ordered collection: An ordered collection maintains the order of the elements based on the sequence we insert or add them in the collection (Refer below example of ArrayList).
Example: We add five elements in an ArrayList in collection as:

ArrayLsit ar = new ArrayLsit();
// Add elements to the Array List
Ar.add(“3”);
Ar.add(“5”);
Ar.add(“1”);
Ar.add(“4”);
Ar.add(“2”);
System.out.println(ar);

This will show the ArrayList as: [3,5,1,4,2]

It means that the elements in the list are in an order in which they were added. This is called ordered and list interface is ordered in java collection.

Sorted collection:  A sorted collection keeps the elements sorted based on sort criteria like ascending or descending. If we sort the ArrayList in above example with collection.sort(ar) then  the list will be shown as:
[1,2,3,4,5]

It means that the elements in the list are not in an order in which they were added rather they are sorted in ascending order. This is called sorted list.
This can be understand with the help set interface also, the set interface is by default sorted in nature, the elements are sorted automatically in set interface and we need not to call the collection.sort() method in set (refer below example of treeset):

TreeSet ts = new TreeSet();
      // Add elements to the tree set
      ts.add("C");
      ts.add("A");
      ts.add("B");
      ts.add("E");
      ts.add("F");
      ts.add("D");
      System.out.println(ts);

This will show the tree set as: [A, B, C, D, E, F]

No comments:

Post a Comment