Tuesday, 18 November 2014

Difference between Arrays.sort() and collections.sort() in java


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.


But internally both are same as collections.sort() uses arrays.sort() only to sort the elements.
The algorithm used for this sorting is mergesort algorithm.

No comments:

Post a Comment