java中Comparable实现对象的比较

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*
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);
   }
}









本文转自 小眼儿 博客园博客,原文链接:http://www.cnblogs.com/hujunzheng/p/3871930.html,如需转载请自行联系原作者
上一篇:mapbox热力图属性


下一篇:Centernet的HearMap绘制及改进