• 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();
    }

    }

  • 相关阅读:
    我是一条内存[转]
    随机翻唱辑 [2006.8.18更新]
    CentOS NTFS 挂载
    grub备忘
    CentOS 使用163软件源
    被车撞了
    爱上苦瓜
    无聊的游戏
    今天去爬山了
    博客搬家了:www.sanv.org
  • 原文地址:https://www.cnblogs.com/shenjun/p/3333576.html
Copyright © 2020-2023  润新知