首页 > 技术文章 > Java—集合框架 Collections.sort()、Comparable接口和Comparator接口

tianxintian22 2017-04-24 14:52 原文

  • Collentions工具类--java.util.Collections

  Collentions是Java集合框架中,用来操作集合对象的工具类,也是Java集合框架的成员,与List、Map和Set是并列的。

  Collections.sort() 排序方法,实现对List对象中的元素进行排序.

package com.test.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class CollectionsTest {

    /**
     * Integer泛型的List进行排序
     */
    public void testSort1(){
        List<Integer> integerList = new ArrayList<Integer>();
        //插入10个100以内不重复的随机整数
        Random random = new Random();
        Integer num;
        for (int i = 0; i < 10; i++) {
            do {
                num = random.nextInt(100);
            } while(integerList.contains(num));
            integerList.add(num);
            System.out.println("成功插入整数:" + num);
        }
        System.out.println("==============排序前=============");
        for (Integer integer : integerList) {
            System.out.print(integer + " ");
        }
        //调用Collections.sort()方法排序
        Collections.sort(integerList);
        System.out.println("==============排序后=============");
        for (Integer integer : integerList) {
            System.out.print(integer + " ");
        }
    }
    /**
     * String泛型的List进行排序
   * 字符串类型进行比较,先数字后字母,数字0-9,字母A-Za-z
*/ public void testSort2() { List<String> stringList = new ArrayList<String>(); //添加3个乱序的String元素 stringList.add("google"); stringList.add("lenovo"); stringList.add("baidu"); System.out.println("==============排序前============="); for (String string : stringList) { System.out.println(string); } Collections.sort(stringList); System.out.println("==============排序后============="); for (String string : stringList) { System.out.println(string); } } public static void main(String[] args) { CollectionsTest ct = new CollectionsTest(); ct.testSort1(); ct.testSort2(); } }
  • Comparable接口和Comparator接口

  在Java中,如果两个对象需要进行排序,那么它们必须是可以比较的。用Comparable这个接口表示某个对象是可以比较的。Comparable相当于给对象定义了默认的排序规则,而如果改用其他规则进行排序,可用Comparator接口,它定义了临时比较规则。Comparable接口和Comparator接口,都是Java集合框架的成员。

  Comparable接口:

  1. 实现该接口表示:这个类的实例可以比较大小,可以进行自然排序;
  2. 定义了默认的比较规则
  3. 其 实现类需实现compareTo()方法
  4. Obja.compareTo(Obj2)方法返回正数表示a比b大,负数表示a比b小,0表示a和b相等

  Comparator接口:

  1. 用于定义临时比较规则,而不是默认比较规则
  2. 其 实现类需要实现compare()方法
  3. 用法:
    Collections.sort(List<T> list, Comparator<? super T> c),根据指定比较器产生的顺序对指定列表进行排序。

   实例:学生系列排序,默认按学生id来排序,先随机生成3个不相同的1000以内的整数做为学生的id;然后再按学生姓名来排序。

package com.test.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class CollectionsTest {

    public void testSort() {
        List<Student> studentList = new ArrayList<Student>();
        List<Integer> studentId = new ArrayList<Integer>();
        Random random = new Random();
        Integer num;
        for (int i = 0; i < 3 ; i++) {
            do {
                num = random.nextInt(1000);
            } while (studentId.contains(num));
            studentId.add(num);
        }

        studentList.add(new Student(studentId.get(0) + "", "Tom"));
        studentList.add(new Student(studentId.get(1) + "", "Jack"));
        studentList.add(new Student(studentId.get(2) + "", "Xiaoming"));
        studentList.add(new Student(1000 + "", "Lily"));
        
        System.out.println("===========排序前=============");
        for (Student student : studentList) {
            System.out.println("学生:" + student.id + "——" + student.name);
        }
        Collections.sort(studentList);
        System.out.println("===========按照id排序后=============");
        for (Student student : studentList) {
            System.out.println("学生:" + student.id + "——" + student.name);
        }
        System.out.println("===========按照姓名排序后========");
        Collections.sort(studentList, new StudentComparator());
        for (Student student : studentList) {
            System.out.println("学生:" + student.id + "——" + student.name);
        }
    }
    
    public static void main(String[] args) {
        CollectionsTest ct = new CollectionsTest();
        ct.testSort();
    }

}

  执行结果:

===========排序前=============
学生:118——Tom
学生:460——Jack
学生:51——Xiaoming
学生:1000——Lily
===========排序后=============
学生:1000——Lily
学生:118——Tom
学生:460——Jack
学生:51——Xiaoming
===========按照姓名排序后========
学生:460——Jack
学生:1000——Lily
学生:118——Tom
学生:51——Xiaoming

  其中,Student类需要实现Comparable接口的compareTo()方法,StudentComparator类需要实现Comparator接口的compare()方法:

  Student.java

package com.test.collection;

import java.util.HashSet;
import java.util.Set;
/**
 * 学生类
 * @author Administrator
 *
 */
public class Student implements Comparable<Student> {
    public String id;
    public String name;
    public Set<Course> courses;//所选课程
    public Student(String id, String name) {
        this.id = id;
        this.name = name;
        this.courses = new HashSet<Course>();//实例化sourses(Set是接口,接口不能被直接实例化)
    }
    @Override
    public int compareTo(Student o) {
        return this.id.compareTo(o.id);
    }
}

   StudentComparator.java

package com.test.collection;

import java.util.Comparator;

public class StudentComparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        return o1.name.compareTo(o2.name);
    }
}

 

推荐阅读