Arrays.sort(T[], Comparator < ? super T > c)
is a method for sorting user-defined object array. The official Java Doc briefly describe what it does, but not much for deep understanding. In this post, I will walk though the key information for deeper understanding of this method.
How to Use Arrays.sort(): A Simple Example
By reading the following example, you can quickly get an idea of how to use this method correctly. A Comparator is defined for comparing Dogs by size and then the Comparator is used as a parameter for the sort method.
Output:
2 1 3
1 2 3
The Strategy Pattern Used in Arrays.sort()
As this is a perfect example of Strategy pattern, it is worth to mention here why strategy pattern is good for this situation. In brief, Strategy pattern enables different algorithms get selected at run-time. In this case, by passing different Comparator, different algorithms can get selected. Based on the example above and now assuming you have another Comparator which compares Dogs by weight instead of by size, you can simply create a new Comparator like the following.
Output:
size=2 weight=50 size=1 weight=30 size=3 weight=40
size=1 weight=30 size=2 weight=50 size=3 weight=40
size=1 weight=30 size=3 weight=40 size=2 weight=50
Comparator is just an interface. Any Comparator that implements this interface can be used during run-time. This is the key idea of Strategy design pattern
Why Use “super”?
It is straightforward if Comparator < T > c
is the parameter, but the second parameter is Comparator< ? super T > c
. < ? super T >
means the type can be T or its super types. Why it allows super types? The answer is: This approach allows using same comparator for all sub
classes. This is almost obvious in the following example.
|
|
Outout:
size=2 size=1 size=3
size=1 size=2 size=3
size=2 size=1 size=3
size=1 size=2 size=3
Summary
To summarize, the takeaway messages from Arrays.sort():
- genetic-super
- stratey pattern
- merge sort-
nlog(n)
time complexity - Java.util.Collections#sort(List
list,Comparator<? super T>c)has similar idea with Arrays.sort.
Reference: