Arrays.sort()的用法

2023-05-16

一、介绍

  • 1、sort(T[] a) 的使用
  • 2、sort(T[] a,int formIndex, int toIndex) 的使用
  • 3、sort(T[] a, Comparator<? supre T> c)的使用
  • 补充:sort(T[] a, Comparator<? supre T> c)类对象比较的使用
  • 补充:那么在参数中会出现super呢?这意味着这类型可以是T或者它的父类型。这就是的该方法可以允许所有子类使用相同的比较器。

Arrays.sort()的作用是对括号中的数组进行排序,时间复杂度O(n*logn),方法返回值为void。 是在原来数组的空间基础上进行升序排序,因此不需要定义一个数组接收它,即不需要返回值。
Arrays.sort()重载了四类方法:
sort(T[] a):对指定T型数组按数字升序排序。
sort(T[] a,int formIndex, int toIndex):对指定T型数组的指定范围按数字升序排序。
sort(T[] a, Comparator<? supre T> c): 根据指定比较器产生的顺序对T型数组进行排序。
sort(T[] a, int formIndex, int toIndex, Comparator<? supre T> c): 根据指定比较器产生的顺序对T型数组的指定范围进行排序。

1、sort(T[] a) 的使用

import java.util.Arrays;
import java.util.Comparator;

public class ArraysSort {
    public static void main(String[] args) {
        int[] a={2,5,4,3,1,8};
        Arrays.sort(a);
        System.out.println(Arrays.toString(a));
    }
}// 结果// [1, 2, 3, 4, 5, 8]

2、sort(T[] a,int formIndex, int toIndex) 的使用

import java.util.Arrays;
import java.util.Comparator;

public class ArraysSort {
    public static void main(String[] args) {
        int[] a={2,5,4,3,1,8};
        Arrays.sort(a,2,5);
        System.out.println(Arrays.toString(a));
    }
}

// 结果
// [2, 5, 1, 3, 4, 8]

3、sort(T[] a, Comparator<? supre T> c)的使用

// 按第一维元素比较二维数组
import java.util.Arrays;
import java.util.Comparator;

public class ArraysSort {
    public static void main(String[] args) {
        int[][] nums=new int[][]{{1,3},{1,2},{4,5},{3,7}};
        //方法一
        Arrays.sort(nums,new Comparator<int[]>(){
            @Override
            public int compare(int[] a,int[] b){
                if(a[0]==b[0]){ // 不明白为什么要这样写  ,自己的基础有问题,不解
                    return a[1]-b[1];
                }else{
                    return a[0]-b[0];
                }
            }
        });
        for (int[] num : nums) {
            System.out.println(Arrays.toString(num));
        }
    }
}

// 结果
/*
[1, 2]
[1, 3]
[3, 7]
[4, 5]
*/


// 按照第二维元素比较二维数组

import java.util.Arrays;
import java.util.Comparator;

public class ArraysSort {
    public static void main(String[] args) {
        int[][] nums=new int[][]{{1,3},{1,2},{4,5},{3,7}};
        //方法一
        Arrays.sort(nums,new Comparator<int[]>(){
            @Override
            public int compare(int[] a,int[] b){
                if(a[1]==b[1]){  //同样不解
                    return a[0]-b[0];
                }else{
                    return a[1]-b[1];
                }
            }
        });

        //方法二
        /*Arrays.sort(nums,(a,b)->a[1]-b[1]);*/
        for (int[] num : nums) {
            System.out.println(Arrays.toString(num));
        }

    }
}
// 结果
/*
[1, 2]
[1, 3]
[4, 5]
[3, 7]
*/

补充:sort(T[] a, Comparator<? supre T> c)类对象比较的使用

import java.util.Arrays;
import java.util.Comparator;

class Dog{
    int size;
    int weight;

    public Dog(int s, int w){
        size = s;
        weight = w;
    }
}

class DogSizeComparator implements Comparator<Dog>{

    @Override
    public int compare(Dog o1, Dog o2) {
        return o1.size - o2.size;
    }
}

class DogWeightComparator implements Comparator<Dog>{  // **在这里尖括号传入的是对象**

    @Override
    public int compare(Dog o1, Dog o2) {
        return o1.weight - o2.weight;
    }
}

public class ArraysSort {
    public static void main(String[] args) {
        Dog d1 = new Dog(2, 50);
        Dog d2 = new Dog(1, 30);
        Dog d3 = new Dog(3, 40);

        Dog[] dogArray = {d1, d2, d3};
        printDogs(dogArray);

        Arrays.sort(dogArray, new DogSizeComparator());
        printDogs(dogArray);

        Arrays.sort(dogArray, new DogWeightComparator());
        printDogs(dogArray);
    }

    public static void printDogs(Dog[] dogs){
        for(Dog d: dogs)
            System.out.print("size="+d.size + " weight=" + d.weight + " ");

        System.out.println();
    }
}

// 结果
/*
size=2 weight=50 size=1 weight=30 size=3 weight=40 
size=1 weight=30 size=2 weight=50 size=3 weight=40 
size=1 weight=30 size=3 weight=40 size=2 weight=50 
*/

补充:那么在参数中会出现super呢?这意味着这类型可以是T或者它的父类型。这就是的该方法可以允许所有子类使用相同的比较器。

import java.util.Arrays;
import java.util.Comparator;

class Animal{
    int size;
}

class Dog extends Animal{
    public Dog(int s){
        size = s;
    }
}

class Cat extends Animal{
    public Cat(int s){
        size  = s;
    }
}

class AnimalSizeComparator implements Comparator<Animal>{
    @Override
    public int compare(Animal o1, Animal o2) {
        return o1.size - o2.size;
    }
}

public class ArraysSort {
    public static void main(String[] args) {
        Dog d1 = new Dog(2);
        Dog d2 = new Dog(1);
        Dog d3 = new Dog(3);

        Dog[] dogArray = {d1, d2, d3};
        printDogs(dogArray);

        Arrays.sort(dogArray, new AnimalSizeComparator());
        printDogs(dogArray);

        System.out.println();
        
        Cat c1 = new Cat(2);
        Cat c2 = new Cat(1);
        Cat c3 = new Cat(3);

        Cat[] catArray = {c1, c2, c3};
        printDogs(catArray);

        Arrays.sort(catArray, new AnimalSizeComparator());
        printDogs(catArray);
    }

    public static void printDogs(Animal[] animals){
        for(Animal a: animals)
            System.out.print("size="+a.size + " ");
        System.out.println();
    }
}

// 结果
/*
size=2 size=1 size=3 
size=1 size=2 size=3 

size=2 size=1 size=3 
size=1 size=2 size=3 
*/

巨人的肩膀:https://www.cnblogs.com/SupremeBoy/p/12717532.html

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Arrays.sort()的用法 的相关文章

  • 在java中使用BUBBLE SORT对二维字符串数组进行排序

    类似的问题已经被问过 但从来没有关于二维字符串数组 因此在尝试了很长时间之后我找不到我想要的 我正在尝试使用 BubbleSort 对 java 中的 2D 字符串数组进行排序 作为输入 我收到一个二维字符串数组 一个表 以及您应该排序的
  • 使用字符串中的变量名称访问变量值,R

    Intro 一个数据集有大量的age year变量 age 1990 age 1991 etc 我有一个字符串值数组length age years 表示这些变量 使得age years 1 回报 age 1990 etc Need 我想搜
  • 如何从嵌套的对象数组中获取每个父级的值

    所以我有多个对象数组 每个对象都包含一个子对象 e g const data id 1 name parent 1 children id c1 name child 1 children id g1 name grand 1 childr
  • 重新排列数组键 php [重复]

    这个问题在这里已经有答案了 我有这个数组 Array 15 gt 13 1 16 gt Mark one answer 19 gt You see a car on the hard shoulder of a motorway with
  • 从 n,k 维矩阵数组中减去 n,k 维矩阵

    如果我有一个数组A A lt array 0 c 4 3 5 for i in 1 5 set seed i A i lt matrix rnorm 12 4 3 如果我有矩阵 B set seed 6 B lt matrix rnorm
  • Minizinc:生成有效的转变

    希望有人能帮助我解决这个问题 最初的问题是生成有效的班次 如下所述 我有这样的数组 m m m o o l l m m m l m m m 具有固定长度 S 其中 m 是工作 o 是办公室 我自由了 我需要确保至少每 6m 就有两个 l 在
  • 每个术语出现的次数

    我得到了一个数组a n 2 where n can be 10 5最大时有n个科目和n个学生 全部编号为 1 2 n a i 0 and a i 1 1 lt i lt n 表示在第 i 个科目中 所有来自a i 0 to a i 1 通过
  • 使用 UISearchBar 过滤数组

    我目前正在使用以下代码来过滤数组并将结果显示在我的 tableView 中 问题是 只有当搜索与确切的单词匹配时 才会返回结果 如何更改数组过滤器以在输入时搜索每个字符 let data Mango Grape Berry Orange A
  • 使用 Java 进行 MongoDB 查询。计算数组中的匹配项

    我在 Mongo 中存储了类似于以下内容的数据 LIST NAME a VALUE z NAME b VALUE y NAME c VALUE x NAME d VALUE w NAME e VALUE v NAME f VALUE u N
  • 读取文本文件并将列存储在数组中

    我的文件看起来像这样 01 01 5 00 1 50 7 50 02 01 4 00 3 00 12 00 02 02 3 00 4 00 12 00 03 01 4 50 3 00 13 50 03 01 7 50 2 50 18 75
  • 如何释放字符指针数组?

    我使用此方法将列表中的值转换为数组 以便在 execvp 系统调用中使用 char list2argarray struct shellvalue values int count char array char malloc count
  • Pygame - 使用 SurfArray 将某种颜色的像素重新着色为另一种颜色(数组切片问题)

    我正在尝试为游戏制作调色板交换功能 并且正在尝试找到一种将某种颜色的像素颜色更改为另一种颜色的方法 我已经能够使用我在教程中找到的这个函数使所有像素具有相同的颜色 def color surface self surface red gre
  • 需要从数组中删除字符串[重复]

    这个问题在这里已经有答案了 我在 for 循环中有一个数组 如下所示 var arr abc 5 city 2 area 2 max choice 我只需要这样的数字 var arr 5 2 2 有人可以在这里帮忙吗 另一种方法是使用转换后
  • 使用静态指针的动态内存分配

    有人可以向我解释一下为什么下面的代码会这样工作吗 这里我已经初始化了outd作为文件中的静态指针code2 c 然后我动态地为其分配内存malloc 从单独文件中的主函数中一次又一次地调用它code1 c 它看起来整个数组以静态方式运行 因
  • 为什么这个二维指针表示法有效,而另一个则无效[重复]

    这个问题在这里已经有答案了 这里我编写了一段代码来打印 3x3 矩阵的对角线值之和 这里我必须将矩阵传递给函数 矩阵被传递给指针数组 代码可以工作 但问题是我必须编写参数的方式如下 int mat 3 以下导致程序崩溃 int mat 3
  • 在 angular2 中过滤数组

    我正在研究如何在 Angular2 中过滤数据数组 我研究过使用自定义管道 但我觉得这不是我想要的 因为它似乎更适合简单的表示转换 而不是过滤大量数据 数组排列如下 getLogs Array
  • 将 2D NumPy 数组按元素相乘并求和

    我想知道是否有一种更快的方法 专用 NumPy 函数来执行 2D NumPy 数组的元素乘法 然后对所有元素求和 我目前使用np sum np multiply A B 其中 A B 是相同维度的 NumPy 数组m x n 您可以使用np
  • 在 C# 中何时使用 ArrayList 而不是 array[]?

    我经常使用一个ArrayList而不是 正常 array 当我使用时 我感觉好像我在作弊 或懒惰 ArrayList 什么时候可以使用ArrayList在数组上 数组是强类型的 并且可以很好地用作参数 如果您知道集合的长度并且它是固定的 则
  • 将文本拆分为数组,同时保留 Swift 中的标点符号

    我想将文本拆分为一个数组 保持标点符号与其余单词分隔开 因此字符串如下 Hello I am Albert Einstein 应该变成这样的数组 Hello I am Albert Einstein 我尝试过sting components
  • 如何在 C# 中获取 Json 数组?

    我有一个像这样的 Json 字符串 我想将它加载到 C 数组中 当我尝试这样做时 我收到异常 我的字符串 customerInformation customerId 123 CustomerName Age 39 Gender Male

随机推荐