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


Difference between Collections.sort() and 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 quicksort in background

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() 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

Solution Worked 0 UpvotesUpvote


Solution Didn't Worked 0 DownvotesDownvote



Search Tags