• java对象比较之Comparable和Comparator


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


    public class Comparable_Comparator {

    public static void main(String... args) throws Exception {

    sortA();
    }

    private static void sortA() {
    // TODO Auto-generated method stub
    List<A> list = new ArrayList<A>();
    list.add(new A(22));
    list.add(new A(10));
    list.add(new A(6));
    list.add(new A(33));
    list.add(new A(21));
    System.out.println(list);
    Collections.sort(list);
    System.out.println(list);
    List<B> list2 = new ArrayList<B>();
    list2.add(new B(22));
    list2.add(new B(10));
    list2.add(new B(6));
    list2.add(new B(33));
    list2.add(new B(21));
    System.out.println(list2);
    Collections.sort(list2,new MyCompator());
    System.out.println(list2);
    }
    }
    class A implements Comparable<A>{
    private int age;

    public A(int age) {
    super();
    this.age = age;
    }
    public int getAge() {
    return age;
    }
    public void setAge(int age) {
    this.age = age;
    }
    public int compareTo(A o) {
    // TODO Auto-generated method stub
    return this.age-o.age;
    }
    @Override
    public String toString() {
    // TODO Auto-generated method stub
    return this.age+"";
    }
    }
    class B {
    private int age;

    public B(int age) {
    super();
    this.age = age;
    }
    public int getAge() {
    return age;
    }
    public void setAge(int age) {
    this.age = age;
    }

    @Override
    public String toString() {
    // TODO Auto-generated method stub
    return this.age+"";
    }

    }


    class MyCompator implements Comparator<B>{

    public int compare(B o1, B o2) {
    // TODO Auto-generated method stub
    return o1.getAge()-o2.getAge();
    }

    }

  • 相关阅读:
    转载-python生成sjf
    111111111111
    【MySQL】使用硬链接的方式删除大表
    【Python】公共类-获取MySQL数据
    【Python】公共类-logger
    文件IO --- sync、fsync、fdatesync
    【Mongo】安装Mongo并配置副本集
    【MySQL】InnoDB 内存管理机制 --- Buffer Pool
    【MySQL】redo log --- 刷入磁盘过程
    Linux 系统的安装
  • 原文地址:https://www.cnblogs.com/shenjun/p/3333576.html
Copyright © 2020-2023  润新知