zoukankan      html  css  js  c++  java
  • 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面试题目【转1】
    让python和C/C++联姻【转】
    python面试模拟真题讲解
    JavaScript真的要一统江湖了
    WebApp
    Linux服务器之SSH
    web服务之http
    SNMP简单网络管理协议
    Storm,Spark和Samza
    Stream computing
  • 原文地址:https://www.cnblogs.com/shenjun/p/3333576.html
Copyright © 2011-2022 走看看