Java排序

2018-10-07  本文已影响0人  正经龙

前言

很多Java算法中都需要用到排序,但是往往在项目开发中并不需要自己实现排序功能,所以必须要熟练使用排序的库函数才能快速的开发出高质量的代码。这篇博客就记录以下常用的数组排序以及List排序,还有用处非常大的自定义对象数组排序

常见数据类型数组排序(正向)

Arrays.sort()

int []x = {3,8,3,2,4,1,4,1,2,2,6,5,5,3,5,1,0,2,4,2,0,4,8,4,2,1,9,4,3,9,6};
Arrays.sort(x);
for(int i =0;i<x.length;i++){
    System.out.print(x[i]);
}

  ##输出结果
  0011112222223333444444555668899

一般对象数组(String、Integer、Character)正向与逆向排序

Arrays.sort(Object[] obj)升序
Arrays.sort(Object[] obj , Comparator.reverseOrder())降序

Java里面并没有给int等自定义数据类型进行降序排列的函数

        String []strings = {"1","x","3","g","5","6","7"};
        Arrays.sort(strings,Comparator.reverseOrder());
        for(int i = 0;i<strings.length;i++){
            System.out.print(strings[i]);
        }

      ###输出
      xg76531

自定义对象数组排序

方法一:实现Comparable接口的compareTo(Object o),然后调用函数自动按照规则排序。

class Name implements Comparable<Name>{
    public String firstName;
    public String lastName;
    public Name(String first,String last){
        this.firstName = first;
        this.lastName = last;
    }
    @Override
    public int compareTo(Name o) {
        int lastCmp = firstName.compareTo(o.firstName);
        return(!(lastCmp==0)?lastCmp:lastName.compareTo(o.lastName));
    }
    public String toString(){
        return firstName + " " + lastName;
    }
}

##############    测试
Name names[] ={new Name("John","Muhaha"),new Name("Gao","Dev"),new Name("Susan","JInjiao")};
        Arrays.sort(names);
        for(int i = 0 ;i<names.length;i++){
            System.out.println(names[i].toString());
        }
################    输出
Gao Dev
John Muhaha
Susan JInjiao

方法二:自定义比较参数,在排序时传入新创建的比较参数实现比较效果(实现compare(Object o1,Object o2))

******自定义类********
class Name2{
    public String firstName;
    public String lastName;
    public Name2(String first,String last){
        this.firstName = first;
        this.lastName = last;
    }
    public String toString(){
        return firstName + " " + lastName;
    }
}
*******创建排序参数********
Comparator<Name2> comparator = new Comparator<Name2>() {
            @Override
            public int compare(Name2 o1, Name2 o2) {
                int bigger = o1.firstName.compareTo(o2.firstName);
                return (!(bigger==0)?bigger:o1.lastName.compareTo(o2.lastName));
            }
        };
******测试************
Arrays.sort(names2,comparator);
        for(int i = 0 ;i<names2.length;i++){
            System.out.println(names2[i].toString());
        }
******输出************
Wang Dev
Xing JInjiao
Yao Muhaha
上一篇 下一篇

猜你喜欢

热点阅读