zoukankan      html  css  js  c++  java
  • Comparable和Comparator

    当对自己定义的数据结构需要进行指定排序的时候,java中给了我们两个接口Comparable和Comparator

    第一种:实现Comparator<T>接口

    public class test {
    
        public static void main(String[] args){
            String[] arr = {"aaa","bbbb","c","dd"};
            Arrays.sort(arr,new LengthCompartor());
            System.out.println(Arrays.toString(arr));
        }
    }
    
    class LengthCompartor implements Comparator<String> {
    
        @Override
        public int compare(String first, String second) {
            return first.length() - second.length();
        }
    }

    第二种:

    public class test {
    
        public static void main(String[] args){
            String[] arr = {"aaa","bbbb","c","dd"};
            Arrays.sort(arr, new Comparator<String>() {
                @Override
                public int compare(String first, String second) {
                    return first.length() - second.length();
                }
            });
            System.out.println(Arrays.toString(arr));
        }
    }

     第三种:要排序的类实现Comparable<T>接口

    public class test {
    
        public static void main(String[] args){
            ArrayList<Employee> list = new ArrayList<>();
            list.add(new Employee(1,1000));
            list.add(new Employee(2,500));
            list.add(new Employee(3,800));
            list.add(new Employee(4,700));
            list.add(new Employee(5,1500));
            Collections.sort(list);
            System.out.println(list);
        }
    }
    
    class Employee implements Comparable<Employee>{
        int salary;
        int id;
    
        public Employee(int id,int salary){
            this.id = id;
            this.salary = salary;
        }
    
        @Override
        public int compareTo(Employee o) {
            return this.salary - o.salary;
        }
    
        @Override
        public String toString() {
            return "Employee{" +
                    "salary=" + salary +
                    ", id=" + id +
                    '}';
        }
    }

     在设计初时有需求就选择Comparable,若后期需要扩展或增加排序需求时,再增加一个比较器Comparator。

  • 相关阅读:
    关于大文本(txt)导入sqlserver2008数据库的一点感想
    欲则不达
    记录下马上两年的大学吧
    osgi使用 equnix框架 Bridge方式搭建方法(部分来源于ibm网站)
    mavan deploy不出repository.xml
    在项目中使用maven私服
    playbook 若干问题
    Maven 3 Felix 4 Eclipse 的搭建与部署(部分转载自别人文章)
    wallwd
    很好的面试记录
  • 原文地址:https://www.cnblogs.com/mxj961116/p/11611328.html
Copyright © 2011-2022 走看看