• comparator和comparable的区别


    Comparable  java.lang  内比较器

    传入一个对象,与自身进行比较,返回差值 正整数 0 负整数。

    实现接口 :public interface Comparable<T>

    接口定义的方法:public int compareTo(T o);

    举例:

        private static  class Student implements Comparable{
            int id;
    
            private Student(int id){
                this.id = id;
            }
    
            @Override
            public int compareTo(Object o) {
                return this.id - ((Student)o).id;
            }
        }
        public void studentCompareTo(){
            Student s1 = new Student(10);
            Student s2 = new Student(20);
    
            int b = s1.compareTo(s2);
            System.out.println(String.valueOf(b));
        }
    

     

    Comparator  java.util 外比较器

    传入两个对象,进行比较

    实现接口:public interface Comparator<T> 

    接口定义的方法  int compare(T o1, T o2);

    举例

       private static class StudentCom1 implements Comparator<Student> {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.id - o2.id;
            }
        }
    
        public void studentCompatator() {
            List<Student> students = new ArrayList<>();
            Student student1 = new Student(10);
            students.add(student1);
            Student student2 = new Student(20);
            students.add(student2);
            Student student3 = new Student(15);
            students.add(student3);
    
            Collections.sort(students, new StudentCom1());
            for (Student student : students)
                System.out.println(student.id);
        }

     

  • 相关阅读:
    HDU1536_SNim_求sg值
    HDU1851_A Simple Game_求sg
    POJ1067_取石子游戏_威佐夫博弈
    HDU1848_Fibonacci again and again_经典的求sg
    POJ2425 && HDU1524_ A Chess Game_树形博弈
    .GB级数据库分区实现高性能
    数据库锁
    热烈庆祝“mysql 集群数据库架构成功”
    linux mysql注意事项
    SQL Server 数据库做读写分离
  • 原文地址:https://www.cnblogs.com/erinchen/p/11719344.html
Copyright © 2020-2023  润新知