zoukankan      html  css  js  c++  java
  • java中Comparable实现对象的比较

    /*
    class A implements Comaprable<A>{
    }
    那么 A x = new A();                           类关系图
    Object o = A;                                 Object
    Comparable c = A;                               |   Comparable
    A 实现了 Comparable 接口嘛                      |-----|-----A
    所以有 o instanceof A == true;
           o instanceof Comparable == true;
    	
        例如ArrayList添加对象实例时,对象实例添加之后先向上转型为Object!内部用Object[]数组接收!
    	Arrays.sort()对Object排序的函数内部就是将 Object 向下转型为Comparable类型。
    	因为每个对象实现了Comparable接口,利用多态性,(Comparable)o1).compareTo(o2)将调用子类的compareTo()方法!
    	
    	((Comparable<Object>)o1).compareTo((Student)o2);
    	((Comparable<XXX>)o1).compareTo((YYY)o2);
    	如果想写泛型那么 XXX 要么是同一类型,要么XXX是YYY的父类!因为我们强转的Comparable是比较XXX类型数据的,
    	而YYY类型满足上面的条件才能成功向上转型为XXX类型!
    */
    
    
    class Person implements Comparable<Person>{
       String name;
       int age;
       Person(){
           name = "";
    	   age = 0;
       }
       Person(String name, int age){
           this.name = name;
    	   this.age = age;
       }
       public String toString(){
           return name + "...." + age;
       }
       
       public boolean equals(Object o){
           Person x = (Person)o;
    	   return name.equals(x.name) && age==x.age;
       }
       
     
       public int compareTo(Person o){
           
           if(name.compareTo(o.name)==0)
    	      return o.age - age;
    	   return o.name.compareTo(name);
       }
    }
    
    class Student implements Comparable<Student>{
         String name;
    	 int age;
    	 public Student(){
    	     name = "";
    		 age = 0;
    	 }
    	 public Student(String name, int age){
    	     this.name = name;
    		 this.age = age;
    	 }
    	 
    	 public int  compareTo(Student o){
    	     
           if(name.compareTo(o.name)==0)
    	      return o.age - age;
    	   return o.name.compareTo(name);
    	 }
    }
    
    
         
    public class Test{
       public static void main(String[] args){
           
            Person p = new Person("fsf", 45);
    		Student s = new Student("faga", 20);
    		Student ss = new Student("fsfdfsf", 456);
    		Comparable xx  =  (Comparable)s;
    		System.out.println(xx);
    		cmp(s,ss);
       }
       public static int cmp(Object o1, Object o2){
    		     //return ((Comparable<Object>)o1).compareTo((Student)o2);
    			 
    		     return ((Comparable)o1).compareTo((Student)o2);
       }
    }
    

      

  • 相关阅读:
    div弹出层
    经典SQL语句
    sql连接及操作
    给flash加上连接
    在c#中图片原比例缩放
    悬浮提示筐
    拖动板块
    IFrame自适应高度
    SQL语句中的日期计算
    注意Request.Cookies["UserID"]的用法
  • 原文地址:https://www.cnblogs.com/hujunzheng/p/3871930.html
Copyright © 2011-2022 走看看