Java Arrays.sort() Method: Usage Guide

In the JDK, Arrays.sort() is a method used for sorting arrays. It takes an array as a parameter and sorts the array elements based on the default sorting rule.

The general steps of using the Arrays.sort() method are as follows:

  1. Create an array that needs to be sorted.
  2. Call the Arrays.sort() method, passing in the array that needs to be sorted as a parameter.
  3. The Arrays.sort() method sorts the array, allowing the original array to be changed by modifying its elements.
  4. After the sorting is completed, you can access the sorted elements by traversing the array.

For example, the following code demonstrates how to use the Arrays.sort() method to sort an array of integers.

import java.util.Arrays;

public class SortExample {
    public static void main(String[] args) {
        int[] numbers = {5, 3, 8, 2, 1};
        
        // 对数组进行排序
        Arrays.sort(numbers);
        
        // 遍历数组并打印排序结果
        for (int number : numbers) {
            System.out.print(number + " ");
        }
    }
}

The output displays as: 1 2 3 5 8.

It is important to note that the Arrays.sort() method by default sorts arrays in ascending order. If you need to sort according to other criteria, you can use the Comparator interface or Comparable interface to implement custom sorting logic and pass it as a parameter to the Arrays.sort() method.

bannerAds