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

  

posted @ 2014-07-27 21:11  hjzqyx  阅读(2198)  评论(0编辑  收藏  举报