Monday, 4 June 2012

Difference Between Collections.sort() and Arrays.sort() ?


Difference Between Collections.sort() and Arrays.sort() ?

Let us look at the basic differences between Collections.sort() and Arrays.sort().
Both the methods are used to sort a group of elements, but which method to use should be decided as per the requirement.
Below are couple of difference between these two methods which gives a clear understanding of  "when /how to implement"

Collections.sort()

Arrays.sort()
Collections.sort operates on a List
Arrays.sort operates on an array

Use Collections.sort() if you're dealing with something that implements the Collection interface - example: ArrayList

Use Arrays.sort() if you're dealing with an Array
Collections.sort() has a input as List so it does a translation of List to array and vice versa which is an additional step while sorting.
So this should be used when you are trying to sort a list.

Arrays.sort is for arrays so the sorting is done directly on the array.
So clearly it should be used when you have a array available with you and you want to sort it.


4 comments:

  1. Can you post some links to verify 3rd point ?

    ReplyDelete
    Replies
    1. Originally Collections.sort() method calls internally Arrays.sort() method.

      Delete
  2. It was very nice article and it is very useful to Java-j2ee learners.We also provide Cub training software online training.

    ReplyDelete