java – arrayListName. What does sort (null) do?
I have a project. The professor gave us some code There is a line in the code that puzzles me:
arrayListName.sort(null);
What exactly does the call to sort (null) do?
The document said: "if the specified comparator is null, all elements in this list must implement the comparable interface, and the natural order of elements should be used. This list must be modifiable, but it does not need to be resizable." What does the natural order of this list mean? The element we try to sort is the phone number
Note: I read Javadoc and I don't know what that means English is not my first language. The professor doesn't teach in English I tried to Google this question, but I'm still confused about what it means
Solution
explain
Assuming that arraylistname is actually a variable of ArrayList type, you call the list #sort method here From its documentation:
Therefore, when the comparator is empty, the method uses the natural ordering of elements
These natural sequences are implemented by the CompareTo method on the project, which implements the comparable interface (documentation) For int, this situation is increasing For strings, this is sorted based on the lexicographical order
Example after using natural sorting:
1,2,3,8,11 "A","B","H","Helicopter","Hello","Tree"
Many classes have implemented this interface Look at documentation At present, it has 287 classes
details
Let's compare it with the actual implementation:
@Override @SuppressWarnings("unchecked") public void sort(Comparator<? super E> c) { final int expectedModCount = modCount; Arrays.sort((E[]) elementData,size,c); if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } modCount++; }
The comparator C is passed to the method arrays#sort. Let's take a look at the excerpt of implementation:
if (c == null) { sort(a,fromIndex,toIndex); }
We then call another arrays#sort method (Implementation) This method sorts elements according to their natural order So no comparator is used