Home > Java > javaTutorial > body text

How to sort using Java's Arrays class

PHPz
Release: 2023-04-27 11:01:06
forward
1080 people have browsed it

1.Arrays.sort(int[] a)

This form is to sort all the elements of an array in order from small to large.

2.Arrays.sort(int[] a, int fromIndex, int toIndex)

This form is to partially sort the array, that is, to sort the array a Sort elements with subscripts from fromIndex to toIndex-1. Note: elements with subscripts to toIndex do not participate in sorting.

3. public static void sort(T[] a,int fromIndex, int toIndex, Comparator c)

Users can Custom sorting.

4. Sort instance

package leetcode;
 
import org.junit.Test;
import java.util.Arrays;
import java.util.Comparator;
 
/**
 * @author zhangyu
 * @Description: Arrays.sort()可以使用内部的比较器进行比较,也可以自己定义比较器进行逆序排序
 * @date 2018/12/10 14:06
 **/
public class ArraysSortTest2 {
    @Test
    public void testArraysSort() {
        Integer[] nums = {5, 2, 1, 3, 4, 9, 0, 7, 8, 6};
        Arrays.sort(nums, new Comparator<Integer>() {
            @Override
            public int compare(Integer a, Integer b) {
                if (a > b) {
                    return -1;
                } else if (a == b) {
                    return 0;
                } else {
                    return 1;
                }
            }
        });
    }
}
Copy after login

The above is the detailed content of How to sort using Java's Arrays class. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template