How to sort an array in Java?

There are several methods commonly used to sort arrays in Java.

  1. By using the sort method from the Arrays class: The Arrays class is a utility class in Java that includes various operations for arrays. The sort method within can be used to arrange the elements of an array in a specific order.
int[] arr = {5, 2, 8, 1, 9};
Arrays.sort(arr);
  1. The sort method provided by the Collections class in Java can be used to sort a List collection. The Collections class is a utility class in Java that includes various operations for collections.
List<Integer> list = new ArrayList<>();
list.add(5);
list.add(2);
list.add(8);
list.add(1);
list.add(9);
Collections.sort(list);
  1. To use a custom sorting algorithm: If you need a custom sorting rule, you can implement the Comparator interface, rewrite the compare method, and then use the sort method of the Arrays class or Collections class for sorting.
int[] arr = {5, 2, 8, 1, 9};
Arrays.sort(arr, new Comparator<Integer>() {
    @Override
    public int compare(Integer o1, Integer o2) {
        // 自定义排序规则,例如按照从大到小的顺序排序
        return o2 - o1;
    }
});

The example above demonstrates sorting an array of integers. For arrays of other types, modifications should be made accordingly. It is important to note that the methods shown sort the array itself and do not create a new sorted array. Additional steps are required to generate a new array if needed.

bannerAds