Difference between Arrays.sort() and Collections.sort()

[19260 views]




Difference between Collections.sort() and Arrays.sort()

Arrays.sort():

Arrays.sort() is a method residing in Arrays class. It is used to sort the Array passed to it. It can be integer array, float array, String array, Array of objects etc.

The time complexity for this method is O(nlogn) as it runs TimSort in background. TimSort algorithm makes use of the Insertion sort and the MergeSort algorithms.

sort() method is best optimized, so if you use this method instead of writing your own, you'll get best results.

import java.util.Arrays; public class JavaTest{ public static void main(String[] args){ String[] names = {"apples", "zen", "delhi"}; Arrays.sort(names); for(String name: names) System.out.print(name+" "); } } //Output: //apple delhi zen
Arrays.sort() uses Dual-Pivot Quicksort algorithm for primitive types (int, String, double, ...) and Mergesort for array of objects.

Collections.sort():

Collections.sort() is used to sort an object which extends List interface. ArrayList and LinkedList extend List interface, so we can sort them using Collections.sort.

Collections.sort() has a time complexity of O(nlogn) as it run merge sort in background

import java.util.*; public class JavaTest{ public static void main(String[] args){ ArrayList<Integer> l = new ArrayList<>(); l.add(15); l.add(2); l.add(43); l.add(0); Collections.sort(l); for(int i=0; i<l.size(); i++) System.out.print(l.get(i)+" "); } } //Output //0 2 15 43
                 



Want to Clear Java Interview? Read Java Interview Notes prepared by Us


Are You Good enough in Java? Prove it!



Comments





Search
Get Answers to your Programming Questions


Recommended Deals ends in








Quiz For You:

Search Tags

    Sorting using Arrays vs Collections in Java