What does arrayListName.sort (null) do?

I have a project, and the professor gave us some code. There is a line in the code that confused me:

arrayListName.sort(null); 

what does the call to sort(null) do exactly?

The document says: "If the specified comparator is zero, then all the elements in this list must implement the Comparable interface, and the natural order of the elements must be used. This list must be modifiable, but it does not need to be changed." What does this mean in the natural order list? The items we are trying to sort are phone numbers.

Note. I am reading javadoc and it is not clear to me what this means. English is not my first language, and the professor does not study this class in English. I tried to ask a question, but I'm still confused about what this means.

+7
java sorting arraylist
source share
2 answers

Description

The assumed arrayListName actually a variable of type ArrayList , then you call the List#sort method here. From the documentation :

default void sort(Comparator<? super E> c)

Sorts this list according to the order invoked by the specified Comparator .

If the specified comparator is null , then all elements in this list should implement the Comparable interface, and the natural order should be used ... p>

Thus, the method uses the natural order of elements when the comparator is null .

This natural ordering is set by the compareTo method for elements when they implement the Compareable interface ( documentation ). For int this view is incremented. For String this type is based on lexicographic order .

Examples after sorting with natural ordering:

 1, 2, 3, 3, 3, 8, 11 "A", "B", "H", "Helicopter", "Hello", "Tree" 

Many classes already implement this interface. Take a look at the documentation . Currently considered 287 classes.


More details

Compare this with the actual implementation :

 @Override @SuppressWarnings("unchecked") public void sort(Comparator<? super E> c) { final int expectedModCount = modCount; Arrays.sort((E[]) elementData, 0, size, c); if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } modCount++; } 

The comparator c is passed to the Arrays#sort method, let's look at an excerpt from the implementation :

 if (c == null) { sort(a, fromIndex, toIndex); } 

We follow this call to another Arrays#sort method ( implementation ). This method sorts items based on their natural ordering . Thus, no comparator is used.

+4
source share

I typed it, and it did not give an error. He sorted the list correctly. This is my code:

 ArrayList<Integer> nums = new ArrayList<Integer>(); nums.add(2); nums.add(4); nums.add(3); nums.add(1); System.out.println(nums); nums.sort(null); System.out.println(nums); 

The output was:

 [2, 4, 3, 1] [1, 2, 3, 4] 

The sort method accepts a Comparator object, and if null is passed, it defaults to natural ordering.

+1
source share

All Articles