{"id":7244,"date":"2023-10-02T21:04:02","date_gmt":"2023-10-02T20:04:02","guid":{"rendered":"https:\/\/www.baeldung.com\/java-arrays-sort-vs-collections-sort"},"modified":"2023-10-02T21:04:02","modified_gmt":"2023-10-02T20:04:02","slug":"difference-between-arrays-sort-and-collections-sort","status":"publish","type":"post","link":"https:\/\/gamefootballmobileanimeiphone.com\/index.php\/2023\/10\/02\/difference-between-arrays-sort-and-collections-sort\/","title":{"rendered":"Difference Between Arrays.sort() and Collections.sort()"},"content":{"rendered":"<p><img src=\"https:\/\/www.baeldung.com\/wp-content\/uploads\/2021\/09\/Java-8-Featured-1024x536.png\" class=\"webfeedsFeaturedVisual wp-post-image\" alt=\"\" decoding=\"async\" style=\"float: left; margin-right: 5px;\" loading=\"lazy\" srcset=\"https:\/\/www.baeldung.com\/wp-content\/uploads\/2021\/09\/Java-8-Featured-1024x536.png 1024w, https:\/\/www.baeldung.com\/wp-content\/uploads\/2021\/09\/Java-8-Featured-300x157.png 300w, https:\/\/www.baeldung.com\/wp-content\/uploads\/2021\/09\/Java-8-Featured-768x402.png 768w, https:\/\/www.baeldung.com\/wp-content\/uploads\/2021\/09\/Java-8-Featured-100x52.png 100w, https:\/\/www.baeldung.com\/wp-content\/uploads\/2021\/09\/Java-8-Featured.png 1200w\" sizes=\"(max-width: 580px) 100vw, 580px\" \/><\/p>\n<h2 id=\"bd-overview\" data-id=\"overview\">1. Overview<\/h2>\n<div class=\"bd-anchor\" id=\"overview\"><\/div>\n<p><a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-sorting\">Sorting<\/a> is a fundamental operation in computer science, essential for data organization and manipulation across various applications.<\/p>\n<p>In this tutorial, we&#8217;ll compare Java&#8217;s commonly used sorting methods: <em>Arrays.sort()<\/em> and <em>Collections.sort()<\/em>. While serving the same primary function\u2014sorting data\u2014each method has its own features, caveats, and optimal use cases.<\/p>\n<h2 id=\"bd-basic-overview\" data-id=\"basic-overview\">2. Basic Overview<\/h2>\n<div class=\"bd-anchor\" id=\"basic-overview\"><\/div>\n<p>Let&#8217;s begin by examining the fundamental differences between these two methods.<\/p>\n<h3 id=\"bd-1-arrayssort\" data-id=\"1-arrayssort\">2.1. <em>Arrays.sort()<\/em><\/h3>\n<div class=\"bd-anchor\" id=\"1-arrayssort\"><\/div>\n<p><strong>The <em>Arrays.sort()<\/em> method is a utility function for sorting arrays in Java.<\/strong> It allows to sort arrays of primitive data types and objects. Whether we&#8217;re working with numerical data or alphabetical strings, <em>Arrays.sort()<\/em> can arrange the elements in ascending order. Additionally, we can modify the behavior with custom comparators for object arrays. This method is part of the <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-util-arrays\"><em>java.util.Arrays<\/em><\/a> class, which provides a suite of utilities for array manipulation.<\/p>\n<h3 id=\"bd-2-collectionssort\" data-id=\"2-collectionssort\">2.2. <em>Collections.sort()<\/em><\/h3>\n<div class=\"bd-anchor\" id=\"2-collectionssort\"><\/div>\n<p><strong>On the other hand, <em>Collections.sort()<\/em> is designed for sorting instances of the <em>List<\/em> interface in Java&#8217;s Collection Framework.<\/strong> Unlike <em>Arrays.sort()<\/em>, which is limited to arrays, <em>Collections.sort()<\/em> can sort more dynamic data structures like <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-arraylist\"><em>ArrayList<\/em><\/a>, <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-linkedlist\"><em>LinkedList<\/em><\/a>, and other classes that implement the <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-collections\"><em>List<\/em><\/a> interface. <em>Collections.sort()<\/em> is a member of the <em>java.util.Collections<\/em> class, a utility class filled with static methods for operating on collections.<\/p>\n<h2 id=\"bd-stability\" data-id=\"stability\">3. Stability<\/h2>\n<div class=\"bd-anchor\" id=\"stability\"><\/div>\n<p>Let&#8217;s imagine that we have a collection of tasks:<\/p>\n<pre><code class=\"language-java\">tasks = new ArrayList&lt;&gt;();\r\ntasks.add(new Task(1, 1, &quot;2023-09-01&quot;));\r\ntasks.add(new Task(2, 2, &quot;2023-08-30&quot;));\r\ntasks.add(new Task(3, 1, &quot;2023-08-29&quot;));\r\ntasks.add(new Task(4, 2, &quot;2023-09-02&quot;));\r\ntasks.add(new Task(5, 3, &quot;2023-09-05&quot;));\r\ntasks.add(new Task(6, 1, &quot;2023-09-03&quot;));\r\ntasks.add(new Task(7, 3, &quot;2023-08-28&quot;));\r\ntasks.add(new Task(8, 2, &quot;2023-09-01&quot;));\r\ntasks.add(new Task(9, 1, &quot;2023-08-28&quot;));\r\ntasks.add(new Task(10, 2, &quot;2023-09-04&quot;));\r\ntasks.add(new Task(11, 3, &quot;2023-08-31&quot;));\r\ntasks.add(new Task(12, 1, &quot;2023-08-30&quot;));\r\ntasks.add(new Task(13, 3, &quot;2023-09-02&quot;));<\/code><\/pre>\n<p>We would like to sort them first by their priority and then by their due date. We&#8217;ll be sorting them with two different approaches. In the first case, we&#8217;ll be using a <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/cs\/stable-sorting-algorithms#stability\">stable algorithm<\/a> provided by <em>Collections<\/em>:<\/p>\n<pre><code class=\"language-java\">final List&lt;Task&gt; tasks = Tasks.supplier.get();\r\nCollections.sort(tasks, Comparator.comparingInt(Task::getPriority));\r\nSystem.out.println(&quot;After sorting by priority:&quot;);\r\nfor (Task task : tasks) {\r\n    System.out.println(task);\r\n}\r\nCollections.sort(tasks, Comparator.comparing(Task::getDueDate));\r\nSystem.out.println(&quot;\\nAfter sorting by due date:&quot;);\r\nfor (Task task : tasks) {\r\n    System.out.println(task);\r\n}<\/code><\/pre>\n<p>Also, we&#8217;ll sort the tasks using a non-stable algorithm. Because Java doesn&#8217;t offer the option to sort a List of reference types using a non-stable algorithm, we have a simple implementation of quicksort:<\/p>\n<pre><code class=\"language-java\">List&lt;Task&gt; tasks = Tasks.supplier.get();\r\nquickSort(tasks, Comparator.comparingInt(Task::getPriority));\r\nSystem.out.println(&quot;After sorting by priority:&quot;);\r\nfor (Task task : tasks) {\r\n    System.out.println(task);\r\n}\r\nquickSort(tasks, Comparator.comparing(Task::getDueDate));\r\nSystem.out.println(&quot;\\nAfter sorting by due date:&quot;);\r\nfor (Task task : tasks) {\r\n    System.out.println(task);\r\n}\r\n<\/code><\/pre>\n<p>The code is overall the same. The only difference is the algorithms used. The sorting is happening in two steps. The first step sorts the tasks by priority and the second by due date.<\/p>\n<p>The difference in the results is subtle but might significantly affect the code&#8217;s functionality and introduce hard-to-debug bugs. The stable version produces the following output:<\/p>\n<pre><code class=\"language-bash\">After sorting by due date:\r\nTask: #9  | Priority: 1 | Due Date: 2023-08-28\r\nTask: #7  | Priority: 3 | Due Date: 2023-08-28\r\nTask: #3  | Priority: 1 | Due Date: 2023-08-29\r\nTask: #12 | Priority: 1 | Due Date: 2023-08-30\r\nTask: #2  | Priority: 2 | Due Date: 2023-08-30\r\nTask: #11 | Priority: 3 | Due Date: 2023-08-31\r\nTask: #1  | Priority: 1 | Due Date: 2023-09-01\r\nTask: #8  | Priority: 2 | Due Date: 2023-09-01\r\nTask: #4  | Priority: 2 | Due Date: 2023-09-02\r\nTask: #13 | Priority: 3 | Due Date: 2023-09-02\r\nTask: #6  | Priority: 1 | Due Date: 2023-09-03\r\nTask: #10 | Priority: 2 | Due Date: 2023-09-04\r\nTask: #5  | Priority: 3 | Due Date: 2023-09-05<\/code><\/pre>\n<p>The tasks are sorted by date, and the previous ordering by priority will be saved when the dates are the same. Whereas the non-stable version gives us this:<\/p>\n<pre><code class=\"language-bash\">After sorting by due date:\r\nTask: #9  | Priority: 1 | Due Date: 2023-08-28\r\nTask: #7  | Priority: 3 | Due Date: 2023-08-28\r\nTask: #3  | Priority: 1 | Due Date: 2023-08-29\r\nTask: #2  | Priority: 2 | Due Date: 2023-08-30\r\nTask: #12 | Priority: 1 | Due Date: 2023-08-30\r\nTask: #11 | Priority: 3 | Due Date: 2023-08-31\r\nTask: #1  | Priority: 1 | Due Date: 2023-09-01\r\nTask: #8  | Priority: 2 | Due Date: 2023-09-01\r\nTask: #4  | Priority: 2 | Due Date: 2023-09-02\r\nTask: #13 | Priority: 3 | Due Date: 2023-09-02\r\nTask: #6  | Priority: 1 | Due Date: 2023-09-03\r\nTask: #10 | Priority: 2 | Due Date: 2023-09-04\r\nTask: #5  | Priority: 3 | Due Date: 2023-09-05<\/code><\/pre>\n<p>The tasks #2 and #12 have the same due date, but the priority is inversed. <strong>This is because a non-stable algorithm produces a non-deterministic behavior when it deals with <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/cs\/stable-sorting-algorithms#stability-matters\">equal but distinguishable items<\/a>.<\/strong><\/p>\n<p><strong>Because primitives don&#8217;t have identity or additional parameters, we can sort them using a non-stable algorithm.<\/strong> The only thing they have is a value, and that&#8217;s why we don&#8217;t care about the stability of the algorithms we&#8217;re using for primitives. As the example above shows, the stability feature is crucial for sorting objects.<\/p>\n<p>That&#8217;s why <em>Arrays.sort()<\/em> uses the same implementation of a non-stable algorithm for primitives, such as <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-quicksort\">Quicksort<\/a> or Dual-Pivot Quicksort. <strong>When dealing with the collections of reference types, both <em>Arrays.sort()<\/em> and <em>Collections.sort()<\/em> use the same implementation, usually <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-merge-sort\">Merge Sort<\/a> or <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/cs\/timsort\">TimSort<\/a>.<\/strong><\/p>\n<h2 id=\"bd-complexity\" data-id=\"complexity\">4. Complexity<\/h2>\n<div class=\"bd-anchor\" id=\"complexity\"><\/div>\n<p>Let&#8217;s make a simple example comparing Merge Sort and Quicksort to show the difference between these algorithms and eventually between <em>Collections.sort()<\/em>\u00a0and\u00a0<em>Arrays.sort()<\/em>. <strong>We&#8217;ll be using simple implementations for both of them.<\/strong> This is done partially because Java doesn&#8217;t provide these algorithms, so we can pick them directly, and partly because the current algorithms have too many tweaks and improvements. Hence, it&#8217;s hard to develop similar test cases for both of them.<\/p>\n<p>We will run the following tests to compare the throughput:<\/p>\n<pre><code class=\"language-java\">@Measurement(iterations = 2, time = 10, timeUnit = TimeUnit.MINUTES)\r\n@Warmup(iterations = 5, time = 10)\r\npublic class PerformanceBenchmark {\r\n    private static final Random RANDOM = new Random();\r\n    private static final int ARRAY_SIZE = 10000;\r\n    private static final int[] randomNumbers = RANDOM.ints(ARRAY_SIZE).toArray();\r\n    private static final int[] sameNumbers = IntStream.generate(() -&gt; 42).limit(ARRAY_SIZE).toArray();\r\n    public static final Supplier&lt;int[]&gt; randomNumbersSupplier = randomNumbers::clone;\r\n    public static final Supplier&lt;int[]&gt; sameNumbersSupplier = sameNumbers::clone;\r\n    @Benchmark\r\n    @BenchmarkMode(Mode.Throughput)\r\n    @Fork(value = 1, jvmArgs = {&quot;-Xlog:gc:file=gc-logs-quick-sort-same-number-%t.txt,filesize=900m -Xmx6gb -Xms6gb&quot;})\r\n    public void quickSortSameNumber() {\r\n        Quicksort.sort(sameNumbersSupplier.get());\r\n    }\r\n    @Benchmark\r\n    @BenchmarkMode(Mode.Throughput)\r\n    @Fork(value = 1, jvmArgs = {&quot;-Xlog:gc:file=gc-logs-quick-sort-random-number-%t.txt,filesize=900m -Xmx6gb -Xms6gb&quot;})\r\n    public void quickSortRandomNumber() {\r\n        Quicksort.sort(randomNumbersSupplier.get());\r\n    }\r\n    @Benchmark\r\n    @BenchmarkMode(Mode.Throughput)\r\n    @Fork(value = 1, jvmArgs = {&quot;-Xlog:gc:file=gc-logs-merge-sort-same-number-%t.txt,filesize=900m -Xmx6gb -Xms6gb&quot;})\r\n    public void mergeSortSameNumber() {\r\n        MergeSort.sort(sameNumbersSupplier.get());\r\n    }\r\n    @Benchmark\r\n    @BenchmarkMode(Mode.Throughput)\r\n    @Fork(value = 1, jvmArgs = {&quot;-Xlog:gc:file=gc-logs-merge-sort-random-number-%t.txt,filesize=900m -Xmx6gb -Xms6gb&quot;})\r\n    public void mergeSortRandomNumber() {\r\n        MergeSort.sort(randomNumbersSupplier.get());\r\n    }\r\n}<\/code><\/pre>\n<p>After running these tests, we got two artifacts: one is the performance metrics, and the other one is the garbage collection log.<\/p>\n<h3 id=\"bd-1-time-complexity\" data-id=\"1-time-complexity\">4.1. Time Complexity<\/h3>\n<div class=\"bd-anchor\" id=\"1-time-complexity\"><\/div>\n<p>Let&#8217;s review the performance metrics for the tests above:<\/p>\n<pre><code class=\"language-bash\">Benchmark                                    Mode  Cnt     Score     Error  Units\r\nPerformanceBenchmark.mergeSortRandomNumber  thrpt    4  1489.983 \u00b1 401.330  ops\/s\r\nPerformanceBenchmark.quickSortRandomNumber  thrpt    4  2757.273 \u00b1  29.606  ops\/s<\/code><\/pre>\n<p><strong>Firstly, using Quicksort to sort random numbers, in general, is almost twice as fast as the MergeSort.<\/strong> The fact that Quicksort happens in place reduces the space complexity affecting the performance, which we discuss in the next section.<\/p>\n<p>Also, we can see that Quicksort may degrade quite rapidly in some cases:<\/p>\n<pre><code class=\"language-bash\">Benchmark                                    Mode  Cnt     Score     Error  Units\r\nPerformanceBenchmark.mergeSortSameNumber    thrpt    4  5295.502 \u00b1  98.624  ops\/s\r\nPerformanceBenchmark.quickSortSameNumber    thrpt    4   118.211 \u00b1   0.117  ops\/s<\/code><\/pre>\n<p>For example, when all the numbers are the same, MergeSort performs much better and is blazingly fast. <strong>Although we&#8217;re using a simple implementation of Quicksort and MergeSort, the behavior is generally similar to their more optimized and complex counterparts.\u00a0\u00a0<\/strong><\/p>\n<p>Please keep in mind that the performance of an algorithm and its time complexity might not correlate as there are many things we should consider additional: space complexity, hidden constant factors, optimization, <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/cs\/quicksort-vs-timsort#1-adaptivity\">adaptivity<\/a>, etc.<\/p>\n<p><strong>The <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-quicksort#1-time-complexity\">upper bound<\/a> for the Quicksort and Dual-Pivot Quicksort is <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-quicksort#1-time-complexity\">higher<\/a> than MergeSort or TimSort. <\/strong>However, due to a series of improvements and checks, performance issues are rendered negligible and, overall, can be ignored. <strong>Thus, we can assume that Merge Sort, TimSort, Quicksort, and Dual-Pivot Quicksort would have the same time complexity.<\/strong><\/p>\n<p>DualPivotQuicksort.sort() method, for example, considers many parameters, such as parallelization, array size, presorted runs, and even the recursion depth. Depending on the primitive types and the size of an array, Java can use different algorithms, like <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-insertion-sort\">Insertion Sort<\/a> or <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-counting-sort\">Counting Sort<\/a>. That&#8217;s why it&#8217;s hard to compare highly optimized algorithms; they would generally produce similar results.<\/p>\n<h3 id=\"bd-2-space-complexity\" data-id=\"2-space-complexity\">4.2. Space Complexity<\/h3>\n<div class=\"bd-anchor\" id=\"2-space-complexity\"><\/div>\n<p><strong>As mentioned previously, while being non-stable, Quicksort and Dual-Pivot Quicksort algorithms\u00a0come with a trade-off as they use less space.<\/strong> Depending on the implementation, they might have at most O(log*n) space complexity. This is a nice feature that might have a significant performance impact. In our case, let&#8217;s concentrate on sorting random numbers.<\/p>\n<p>While the time complexity of these algorithms is considered roughly the same, we have dramatic differences in the performance:<\/p>\n<pre><code class=\"language-bash\">Benchmark                                    Mode  Cnt     Score     Error  Units\r\nPerformanceBenchmark.mergeSortRandomNumber  thrpt    4  1489.983 \u00b1 401.330  ops\/s\r\nPerformanceBenchmark.quickSortRandomNumber  thrpt    4  2757.273 \u00b1  29.606  ops\/s<\/code><\/pre>\n<p>To investigate this difference, we could look at the garbage collection logs. We&#8217;ll be using IBM Garbage Collection and Memory Visualizer:<\/p>\n<table style=\"border-collapse: collapse;width: 84.3481%;height: 226px;border: 1px solid black\">\n<tbody>\n<tr style=\"height: 24px;background: #4e9359;color: #fff;border: 1px solid black\">\n<td class=\"header\" style=\"width: 75.8613%;height: 24px\">Variant<\/td>\n<td class=\"header\" style=\"width: 12.4758%;height: 24px;border: 1px solid black\">mergeSort<\/td>\n<td class=\"header\" style=\"width: 42.743%;height: 24px\">quickSort<\/td>\n<\/tr>\n<tr style=\"height: 24px;border: 1px solid black\">\n<td class=\"resultsodd\" style=\"width: 75.8613%;height: 24px\">Forced collection count<\/td>\n<td class=\"resultsodd\" style=\"width: 12.4758%;height: 24px;border: 1px solid black\">0<\/td>\n<td class=\"resultsodd\" style=\"width: 42.743%;height: 24px\">0<\/td>\n<\/tr>\n<tr style=\"height: 24px;border: 1px solid black;background: #63b175;color: #fff\">\n<td class=\"results\" style=\"width: 75.8613%;height: 24px\">Full collections<\/td>\n<td class=\"results\" style=\"width: 12.4758%;height: 24px;border: 1px solid black\">0<\/td>\n<td class=\"results\" style=\"width: 42.743%;height: 24px\">0<\/td>\n<\/tr>\n<tr style=\"height: 24px;border: 1px solid black\">\n<td class=\"resultsodd\" style=\"width: 75.8613%;height: 24px\">GC Mode<\/td>\n<td class=\"resultsodd\" style=\"width: 12.4758%;height: 24px;border: 1px solid black\">G1<\/td>\n<td class=\"resultsodd\" style=\"width: 42.743%;height: 24px\">G1<\/td>\n<\/tr>\n<tr style=\"height: 18px;border: 1px solid black;background: #63b175;color: #fff\">\n<td class=\"results\" style=\"width: 75.8613%;height: 18px\">Mean garbage collection pause (ms)<\/td>\n<td class=\"results\" style=\"width: 12.4758%;height: 18px;border: 1px solid black\">0.33<\/td>\n<td class=\"results\" style=\"width: 42.743%;height: 18px\">0.47<\/td>\n<\/tr>\n<tr style=\"height: 21px;border: 1px solid black\">\n<td class=\"resultsodd\" style=\"width: 75.8613%;height: 21px\">Number of collections triggered by allocation failure<\/td>\n<td class=\"resultsodd\" style=\"width: 12.4758%;height: 21px;border: 1px solid black\">26848<\/td>\n<td class=\"resultsodd\" style=\"width: 42.743%;height: 21px\">588<\/td>\n<\/tr>\n<tr style=\"height: 10px;border: 1px solid black;background: #63b175;color: #fff\">\n<td class=\"results\" style=\"width: 75.8613%;height: 10px\">Proportion of time spent in garbage collection pauses (%)<\/td>\n<td class=\"results\" style=\"width: 12.4758%;height: 10px;border: 1px solid black\">0.72<\/td>\n<td class=\"results\" style=\"width: 42.743%;height: 10px\">0.02<\/td>\n<\/tr>\n<tr style=\"height: 27px;border: 1px solid black\">\n<td class=\"resultsodd\" style=\"width: 75.8613%;height: 27px\">Proportion of time spent in stop-the-world garbage collection pauses (%)<\/td>\n<td class=\"resultsodd\" style=\"width: 12.4758%;height: 27px;border: 1px solid black\">0.72<\/td>\n<td class=\"resultsodd\" style=\"width: 42.743%;height: 27px\">0.02<\/td>\n<\/tr>\n<tr style=\"height: 22px;border: 1px solid black;background: #63b175;color: #fff\">\n<td class=\"results\" style=\"width: 75.8613%;height: 22px\">Proportion of time spent unpaused (%)<\/td>\n<td class=\"results\" style=\"width: 12.4758%;height: 22px;border: 1px solid black\">99.28<\/td>\n<td class=\"results\" style=\"width: 42.743%;height: 22px\">99.98<\/td>\n<\/tr>\n<tr style=\"height: 10px;border: 1px solid black\">\n<td class=\"resultsodd\" style=\"width: 75.8613%;height: 10px\">Young collections &#8211; Mean garbage collection pause (ms)<\/td>\n<td class=\"resultsodd\" style=\"width: 12.4758%;height: 10px;border: 1px solid black\">0.33<\/td>\n<td class=\"resultsodd\" style=\"width: 42.743%;height: 10px\">0.47<\/td>\n<\/tr>\n<tr style=\"height: 22px;border: 1px solid black;background: #63b175;color: #fff\">\n<td class=\"results\" style=\"width: 75.8613%;height: 22px\">Young collections &#8211; Mean interval between collections (ms)<\/td>\n<td class=\"results\" style=\"width: 12.4758%;height: 22px;border: 1px solid black\">46.6<\/td>\n<td class=\"results\" style=\"width: 42.743%;height: 22px\">2124<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>As we can see, the number of garbage collection events is significantly higher for MergeSort (26848 vs. 588), and it&#8217;s understandable as this algorithm uses more space.<\/p>\n<h3 id=\"bd-3-optimization\" data-id=\"3-optimization\">4.3. Optimization<\/h3>\n<div class=\"bd-anchor\" id=\"3-optimization\"><\/div>\n<p>Because Merge Sort and TimSort require more space, using a non-stable algorithm for primitives is the optimization step, assuming that Quicksort and Dual-Pivot Quicksort degradation to O(n^2) is negligible. Technically, it&#8217;s possible to use a non-stable sorting algorithm for a collection of reference types and get a boost in performance.<strong> This can be done if stability isn&#8217;t important or equal objects are non-distinguishable.<\/strong><\/p>\n<p>One of the improvements we can use for wrapper classes is to convert them into primitives, do the sorting, and convert them back. Let&#8217;s consider the following test:<\/p>\n<pre><code class=\"language-java\">@Measurement(iterations = 2, time = 10, timeUnit = TimeUnit.MINUTES)\r\n@Warmup(iterations = 5, time = 10)\r\n@Fork(value = 2)\r\npublic class ObjectOverheadBenchmark {\r\n    private static final ThreadLocalRandom RANDOM = ThreadLocalRandom.current();\r\n    @State(Scope.Benchmark)\r\n    public static class Input {\r\n        public Supplier&lt;List&lt;Integer&gt;&gt; randomNumbers = () -&gt; RANDOM.ints().limit(10000).boxed().collect(Collectors.toList());\r\n    }\r\n    @Benchmark\r\n    @BenchmarkMode(Mode.Throughput)\r\n    public void sortingPrimitiveArray(Input input, Blackhole blackhole) {\r\n        final int[] array = input.randomNumbers.get().stream().mapToInt(Integer::intValue).toArray();\r\n        Arrays.sort(array);\r\n        final List&lt;Integer&gt; result = Arrays.stream(array).boxed().collect(Collectors.toList());\r\n        blackhole.consume(result);\r\n    }\r\n    @Benchmark\r\n    @BenchmarkMode(Mode.Throughput)\r\n    public void sortingObjectArray(Input input, Blackhole blackhole) {\r\n        final Integer[] array = input.randomNumbers.get().toArray(new Integer[0]);\r\n        Arrays.sort(array);\r\n        blackhole.consume(array);\r\n    }\r\n    \r\n    @Benchmark\r\n    @BenchmarkMode(Mode.Throughput)\r\n    public void sortingObjects(Input input, Blackhole blackhole) {\r\n        final List&lt;Integer&gt; list = input.randomNumbers.get();\r\n        Collections.sort(list);\r\n        blackhole.consume(list);\r\n    }\r\n}<\/code><\/pre>\n<p>The fact that we&#8217;re using\u00a0<em>Arrays.sort()<\/em> here significantly boosts our performance\u00a0<em>Collection.sort():<\/em><\/p>\n<pre><code class=\"language-bash\">Benchmark                                       Mode  Cnt     Score     Error  Units\r\nObjectOverheadBenchmark.sortingObjectArray     thrpt    4   982.849 \u00b1  19.201  ops\/s\r\nObjectOverheadBenchmark.sortingObjects         thrpt    4   976.778 \u00b1  10.580  ops\/s\r\nObjectOverheadBenchmark.sortingPrimitiveArray  thrpt    4  1998.818 \u00b1 373.654  ops\/s<\/code><\/pre>\n<p>Sorting an\u00a0<em>int[]<\/em> produces more than a 100% increase in performance.<\/p>\n<h2 id=\"bd-implementation-details-of-arrayssort-and-collectionssort\" data-id=\"implementation-details-of-arrayssort-and-collectionssort\">5. Implementation Details of <em>Arrays.sort()<\/em> and <em>Collections.sort()<\/em><\/h2>\n<div class=\"bd-anchor\" id=\"implementation-details-of-arrayssort-and-collectionssort\"><\/div>\n<p><strong>Please note that the algorithms and tests used in the previous sections. They don&#8217;t reflect the library implementation&#8217;s performance, as they have more complex processes that allow them to optimize specific cases.<\/strong> The tests are presented only to provide more visual information about the inner workings of the simple implementation for these two kinds of algorithms.<\/p>\n<p>It&#8217;s virtually impossible to compare <em>Collections.sort()\u00a0<\/em>and\u00a0<em>Arrays.sort()<\/em> without their underlying algorithms.<\/p>\n<p><strong>The underlying algorithms are the crucial part contributing to these two methods&#8217; complexity and performance.<\/strong>\u00a0Because\u00a0<em>Collections.sort()<\/em> is implemented with stability in mind, they use Merge Sort or TimSort. At the same time, sorting primitives doesn&#8217;t require this property and can use Quicksort or Dual-Pivot Quicksort.<\/p>\n<p>To better understand these methods, we looked at the sorting algorithms they use directly.<\/p>\n<h2 id=\"bd-conclusion\" data-id=\"conclusion\">6. Conclusion<\/h2>\n<div class=\"bd-anchor\" id=\"conclusion\"><\/div>\n<p>Sorting is one of the cornerstone operations in computer science, enabling efficient data manipulation across many applications. By understanding the differences between algorithms, we can make more informed decisions when coding and optimizing for performance and functionality according to your specific requirements.<\/p>\n<p>Thus, although this article aims to highlight the difference between <em>Collections.sort()\u00a0<\/em>and\u00a0<em>Arrays.sort().\u00a0<\/em>It is also a great guide to understanding the differences between different sorting algorithms.\u00a0As always, the code for the implementation of this algorithm can be found <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/github.com\/eugenp\/tutorials\/tree\/master\/core-java-modules\/core-java-collections-5\">over\u00a0on GitHub<\/a>.<\/p>\n<p><Img align=\"left\" border=\"0\" height=\"1\" width=\"1\" alt=\"\" style=\"border:0;float:left;margin:0;padding:0;width:1px!important;height:1px!important;\" hspace=\"0\" src=\"https:\/\/feeds.feedblitz.com\/~\/i\/797158418\/0\/baeldung\"><\/p>\n<div style=\"clear:both;padding-top:0.2em;\"><a title=\"Like on Facebook\" href=\"https:\/\/feeds.feedblitz.com\/_\/28\/797158418\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/fblike20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Pin it!\" href=\"https:\/\/feeds.feedblitz.com\/_\/29\/797158418\/baeldung,https%3A%2F%2Fwww.baeldung.com%2Fwp-content%2Fuploads%2F2021%2F09%2FJava-8-Featured-1024x536.png\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/pinterest20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Tweet This\" href=\"https:\/\/feeds.feedblitz.com\/_\/24\/797158418\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/twitter20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Subscribe by email\" href=\"https:\/\/feeds.feedblitz.com\/_\/19\/797158418\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/email20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Subscribe by RSS\" href=\"https:\/\/feeds.feedblitz.com\/_\/20\/797158418\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/rss20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a rel=\"NOFOLLOW\" title=\"View Comments\" href=\"https:\/\/www.baeldung.com\/java-arrays-collections-sort-methods#respond\"><img decoding=\"async\" height=\"20\" style=\"border:0;margin:0;padding:0;\" src=\"https:\/\/assets.feedblitz.com\/i\/comments20.png\"><\/a>&#160;<a title=\"Follow Comments via RSS\" href=\"https:\/\/www.baeldung.com\/java-arrays-collections-sort-methods\/feed\"><img decoding=\"async\" height=\"20\" style=\"border:0;margin:0;padding:0;\" src=\"https:\/\/assets.feedblitz.com\/i\/commentsrss20.png\"><\/a>&#160;<\/div>\n\n<h2><b>Commercials Cooperation Advertisements:<\/b><\/h2>\r\n<p><br>(1) IT Teacher IT Freelance<br> <\/p>\r\n<a href=https:\/\/itteacheritfreelance.hk\/wordpress><img src=http:\/\/gamefootballmobileanimeiphone.com\/wp-content\/uploads\/2023\/09\/ITTeacherITFreelance-Website.png alt=IT\u96fb\u8166\u88dc\u7fd2 java\u88dc\u7fd2 \u70ba\u5927\u5bb6\u914d\u5c0d\u96fb\u8166\u88dc\u7fd2,IT freelance, \u79c1\u4eba\u8001\u5e2b, PHP\u88dc\u7fd2,CSS\u88dc\u7fd2,XML,Java\u88dc\u7fd2,MySQL\u88dc\u7fd2,graphic design\u88dc\u7fd2,\u4e2d\u5c0f\u5b78ICT\u88dc\u7fd2,\u4e00\u5c0d\u4e00\u79c1\u4eba\u88dc\u7fd2\u548cFreelance\u81ea\u7531\u5de5\u4f5c\u914d\u5c0d\u3002\/><\/a><p><a href=https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/findteacher>\u7acb\u523b\u8a3b\u518a\u53ca\u5831\u540d\u96fb\u8166\u88dc\u7fd2\u8ab2\u7a0b\u5427! <\/a><br>\r\n\r\n\u7535\u5b50\u8ba1\u7b97\u673a -\u6559\u80b2 -IT \u96fb\u8166\u73ed\u201d ( IT\u96fb\u8166\u88dc\u7fd2 ) \u63d0\u4f9b\u4e00\u500b\u65b9\u4fbf\u7684\u7535\u5b50\u8ba1\u7b97\u673a \u6559\u80b2\u5e73\u53f0, \u70ba\u5927\u5bb6\u914d\u5c0d\u4fe1\u606f\u6280\u672f, \u96fb\u8166 \u8001\u5e2b, IT freelance \u548c programming expert. \u8b93\u5927\u5bb6\u65b9\u4fbf\u5730\u5c31\u80fd\u627e\u5230\u5408\u9069\u7684\u96fb\u8166\u88dc\u7fd2, \u96fb\u8166\u73ed, \u5bb6\u6559, \u79c1\u4eba\u8001\u5e2b.  <br>\r\n\r\nWe are a education and information platform which you can find a IT private tutorial teacher or freelance. <br>\r\n\r\nAlso we provide different information about information technology, Computer, programming, mobile, Android, apple, game, movie, anime, animation\u2026 \r\n<\/p>\n<p><br>(2) ITSec<br> <\/p><a href=https:\/\/itsec.vip><img src=http:\/\/gamefootballmobileanimeiphone.com\/wp-content\/uploads\/2023\/09\/ITSec-Main-Promotion-Image.png alt= https:\/\/itsec.vip\/\r\nSecure Your Computers from Cyber Threats and mitigate risks with professional services to defend Hackers.  \r\nITSec provide IT Security and Compliance Services, including IT Compliance Services, Risk Assessment, IT Audit, Security Assessment and Audit, ISO 27001 Consulting and Certification, GDPR Compliance Services, Privacy Impact Assessment (PIA), Penetration test, Ethical Hacking, Vulnerabilities scan, IT Consulting, Data Privacy Consulting, Data Protection Services, Information Security Consulting, Cyber Security Consulting, Network Security Audit, Security Awareness Training.\/><\/a> \r\n<br><br> \r\n<p><a href=https:\/\/itsec.vip>www.ITSec.vip<\/a> <br> <br> \r\n<p><a href=https:\/\/sraa.com.hk>www.Sraa.com.hk<\/a> <br> <br> \r\n<p><a href=https:\/\/itsec.hk>www.ITSec.hk<\/a> <br> <br> \r\n<p><a href=https:\/\/penetrationtest.hk>www.Penetrationtest.hk<\/a> <br> <br> \r\n<p><a href=https:\/\/itseceu.uk>www.ITSeceu.uk<\/a> <br> <br> \r\nSecure Your Computers from Cyber Threats and mitigate risks with professional services to defend Hackers. <br><br>\r\nITSec provide IT Security and Compliance Services, including IT Compliance Services, Risk Assessment, IT Audit, Security Assessment and Audit, ISO 27001 Consulting and Certification, GDPR Compliance Services, Privacy Impact Assessment (PIA), Penetration test, Ethical Hacking, Vulnerabilities scan, IT Consulting, Data Privacy Consulting, Data Protection Services, Information Security Consulting, Cyber Security Consulting, Network Security Audit, Security Awareness Training. \r\n<br><br>Contact us right away. <br><br>Email (Prefer using email to contact us): <br>SalesExecutive@ITSec.vip<\/p>","protected":false},"excerpt":{"rendered":"<p><img decoding=\"async\" src=\"https:\/\/www.baeldung.com\/wp-content\/uploads\/2021\/09\/Java-8-Featured-1024x536.png\" class=\"webfeedsFeaturedVisual wp-post-image\" alt=\"\" loading=\"lazy\"><\/p>\n<p>Compare two Java&#8217;s commonly used sorting methods: Arrays.sort() and Collections.sort().<\/p>\n<div><a title=\"Like on Facebook\" href=\"https:\/\/feeds.feedblitz.com\/_\/28\/797158418\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/fblike20.png\"><\/a>\u00a0<a title=\"Pin it!\" href=\"https:\/\/feeds.feedblitz.com\/_\/29\/797158418\/baeldung,https%3A%2F%2Fwww.baeldung.com%2Fwp-content%2Fuploads%2F2021%2F09%2FJava-8-Featured-1024x536.png\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/pinterest20.png\"><\/a>\u00a0<a title=\"Tweet This\" href=\"https:\/\/feeds.feedblitz.com\/_\/24\/797158418\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/twitter20.png\"><\/a>\u00a0<a title=\"Subscribe by email\" href=\"https:\/\/feeds.feedblitz.com\/_\/19\/797158418\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/email20.png\"><\/a>\u00a0<a title=\"Subscribe by RSS\" href=\"https:\/\/feeds.feedblitz.com\/_\/20\/797158418\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/rss20.png\"><\/a>\u00a0<a rel=\"NOFOLLOW\" title=\"View Comments\" href=\"https:\/\/www.baeldung.com\/java-arrays-collections-sort-methods#respond\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/comments20.png\"><\/a>\u00a0<a title=\"Follow Comments via RSS\" href=\"https:\/\/www.baeldung.com\/java-arrays-collections-sort-methods\/feed\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/commentsrss20.png\"><\/a>\u00a0<\/div>\n","protected":false},"author":291,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"site-container-style":"default","site-container-layout":"default","site-sidebar-layout":"default","disable-article-header":"default","disable-site-header":"default","disable-site-footer":"default","disable-content-area-spacing":"default","footnotes":""},"categories":[22],"tags":[61,122,127,129,124,128,125,132,131,133,126,130,123,66,94,88,97,56,64,65,60,112,40,75,95,104,33,120,105,101,98,115,30,29,41,86,70,69,68,72,71,26,118,108,87,46,55,48,52,54,51,50,83,62,58,57,109,35,59,63,85,79,82,96,80,27,81,114,44,42,43,45,38,39,110,117,100,111,116,73,89,90,92,91,93,84,78,37,102,34,36,77,67,74,99,113,119,28,121,32,47,49,53,103,31,76],"class_list":["post-7244","post","type-post","status-publish","format-standard","hentry","category-mobile","tag-airpods","tag-anime","tag-anime-characters","tag-anime-cosplay","tag-anime-edits","tag-anime-merchandise","tag-anime-movies","tag-anime-news","tag-anime-recommendations","tag-anime-reviews","tag-anime-series","tag-anime-streaming","tag-animes","tag-app-store","tag-app-store-samsung","tag-appgallery","tag-appgallery-oneplus","tag-apple","tag-apple-music","tag-apple-tv","tag-apple-watch","tag-bbc-sport","tag-best-mobile-games","tag-bixby","tag-bixby-xiaomi","tag-champions-league","tag-cyberpunk","tag-cyberpunk-2077","tag-fantasy-football","tag-fifa","tag-football","tag-formula-1","tag-fortnite","tag-free-fire","tag-free-mobile-games","tag-freebuds-pro","tag-galaxy-a52","tag-galaxy-note-20","tag-galaxy-s21","tag-galaxy-watch-4","tag-galaxy-z-fold-3","tag-game","tag-games","tag-golf","tag-harmonyos","tag-how-to-backup-iphone","tag-how-to-factory-reset-iphone","tag-how-to-reset-iphone","tag-how-to-restore-iphone","tag-how-to-unlock-iphone","tag-how-to-unlock-iphone-5","tag-how-to-unlock-iphone-6","tag-huawei","tag-ios","tag-ipad","tag-iphone","tag-live-soccer","tag-lol","tag-macbook","tag-macos","tag-mate-40-pro","tag-mi-11-lite","tag-mi-home-security-camera-basic-1080p","tag-mi-home-security-camera-basic-1080p-huawei","tag-mi-smart-band-6","tag-minecraft","tag-miui","tag-mlb-scores","tag-mobile-game-design","tag-mobile-game-development","tag-mobile-game-marketing","tag-mobile-game-monetization","tag-mobile-games","tag-mobile-gaming","tag-nba-scores","tag-nba-standings","tag-nfl","tag-nfl-scores","tag-nhl-scores","tag-one-ui","tag-oneplus","tag-oneplus-9-pro","tag-oneplus-buds-pro","tag-oneplus-nord-ce-5g","tag-oxygenos","tag-p40-pro-plus","tag-poco-x3-pro","tag-pokemon","tag-premier-league","tag-pubg","tag-pubg-mobile","tag-redmi-note-10-pro","tag-samsung","tag-samsung-pay","tag-soccer","tag-sports","tag-steam","tag-steeam","tag-top-10-anime","tag-valorant","tag-when-do-the-iphone-7-come-out","tag-when-does-the-iphone-7-come-out","tag-when-is-the-iphone-7-coming-out","tag-world-cup","tag-xbox-series-x","tag-xiaomi"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/gamefootballmobileanimeiphone.com\/index.php\/wp-json\/wp\/v2\/posts\/7244","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/gamefootballmobileanimeiphone.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/gamefootballmobileanimeiphone.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/gamefootballmobileanimeiphone.com\/index.php\/wp-json\/wp\/v2\/users\/291"}],"replies":[{"embeddable":true,"href":"https:\/\/gamefootballmobileanimeiphone.com\/index.php\/wp-json\/wp\/v2\/comments?post=7244"}],"version-history":[{"count":1,"href":"https:\/\/gamefootballmobileanimeiphone.com\/index.php\/wp-json\/wp\/v2\/posts\/7244\/revisions"}],"predecessor-version":[{"id":7245,"href":"https:\/\/gamefootballmobileanimeiphone.com\/index.php\/wp-json\/wp\/v2\/posts\/7244\/revisions\/7245"}],"wp:attachment":[{"href":"https:\/\/gamefootballmobileanimeiphone.com\/index.php\/wp-json\/wp\/v2\/media?parent=7244"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/gamefootballmobileanimeiphone.com\/index.php\/wp-json\/wp\/v2\/categories?post=7244"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/gamefootballmobileanimeiphone.com\/index.php\/wp-json\/wp\/v2\/tags?post=7244"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}