Skip to content

Commit 6653d80

Browse files
author
yennj12
committed
update
1 parent 2bed7c7 commit 6653d80

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

doc/cheatsheet/java_trick.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -554,6 +554,13 @@ int[][] intervals = new int[][]{ {15,20}, {0,30}, {5,10} };
554554

555555

556556
### 1-4-3) Sort List VS Array
557+
558+
#### In Summary !!!!
559+
560+
- `Arrays.sort` for array sorting
561+
- `Collections.sort` for list, HashMap .. sorting
562+
563+
557564
```java
558565
// java
559566
// LC 214

leetcode_java/src/main/java/dev/Sorting/ArraySortTest.java

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,55 @@ public void testOnArrayVal1(){
2424
*/
2525
System.out.println(">>> (before) arr = " + Arrays.asList(arr));
2626

27+
/**
28+
* Why for hashMap, List we use `Collections.sort`
29+
* but for array, we use `Arrays.sort` ?
30+
*
31+
*
32+
* -> In brief, `array` is the basic data structure in java,
33+
* it's a fixed size (not dynamic), `Arrays utility` offers basic
34+
* functions for support operation on such structures
35+
*
36+
* while `collections` is the dynamic data structure,
37+
* (e.g. ArrayList, LinkedList, HashMap...)
38+
*
39+
*
40+
*
41+
*
42+
* 1)
43+
*
44+
* - Collections Framework:
45+
*
46+
* Java provides the Collections Framework to
47+
* work with dynamic collections that have flexible sizes,
48+
* such as List, Set, and Queue. Since List is part of the framework,
49+
* Collections.sort() is used for sorting List objects.
50+
* The framework provides numerous utilities for adding, removing, and sorting elements.
51+
*
52+
* - Arrays:
53+
*
54+
* Arrays are a more primitive data structure in Java.
55+
* The Arrays.sort() method is provided by the Arrays utility
56+
* class specifically for sorting arrays, which do not have the flexibility
57+
* of the List interface. Arrays are fixed-size,
58+
* and Arrays.sort() provides an efficient way to sort them.
59+
*
60+
*
61+
* 2) Key Differences Between Sorting with Arrays.sort() vs Collections.sort():
62+
*
63+
* - Arrays.sort():
64+
* Works with primitive arrays (e.g., int[], double[])
65+
* and arrays of objects. It is optimized for the underlying
66+
* fixed-size nature of arrays and is directly implemented in the Arrays class.
67+
*
68+
*
69+
* - Collections.sort():
70+
* Works only with List types (e.g., ArrayList, LinkedList, etc.).
71+
* It is implemented in the Collections utility class and requires
72+
* that the data be in a List form.
73+
*
74+
*/
75+
2776
/**
2877
* NOTE !!!
2978
*

0 commit comments

Comments
 (0)