java – Arrays. Sort (object []) did not throw ClassCastException
•
Java
Code:
public class CompareTest { public static void main(String[] args) { ArrayList list = new ArrayList(); (list).add(new Comparetest()); Arrays.sort(list.toArray()); //Does not throw Exception,why ? Collections.sort(list); //throws ClassCastException } }
According to Java doc: arrays#sort
According to the prompt, the specified object array is sorted in ascending order, and its elements are naturally sorted All elements in the array must implement the comparable interface
Why won't arrays#sort throw the ClassCastException declared by Javadoc?
Solution
Because arrays The source code of sort() has this shortcut:
int nRemaining = hi - lo; if (nRemaining < 2) return; // Arrays of size 0 and 1 are always sorted
Therefore, it does not check whether the elements of the array implement comparable, because it does not have to sort an array with only one element
Note that Javadoc does not guarantee to throw ClassCastException
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码