Java 接口:比较对象的大小

 1 package com.bytezreo.interfacetest;
 2 
 3 /**
 4  * 
 5  * @Description   接口:比较对象的大小
 6  * @author Bytezero·zhenglei!        Email:420498246@qq.com
 7  * @version
 8  * @date 下午9:07:52
 9  * @
10  *
11  */
12 
13 public class ComparableCircleTest {
14 
15     public static void main(String[] args) {
16         
17         ComparableCircle c1 = new ComparableCircle(3.4);
18         ComparableCircle c2 = new ComparableCircle(3.6);
19         
20         int compareValue = c1.compareTo(c2);
21         if(compareValue > 0) {
22             System.out.println("c1对象大");
23         }else if(compareValue < 0) {
24             System.out.println("c2对象大");
25         }else {
26              System.out.println("c1与c2一样大");
27         }
28         
29         
30         
31         
32     }
33 }
 1 package com.bytezreo.interfacetest;
 2 
 3 
 4 public class ComparableCircle extends Circle implements CompareObject {
 5 
 6     
 7     public ComparableCircle(double radius) {
 8         super(radius);
 9     }
10     @Override
11     public int compareTo(Object o) {
12         if(this == o) {
13             return 0;
14         }
15         
16         if(o instanceof ComparableCircle ) {
17             ComparableCircle c = (ComparableCircle)o;
18             
19             //错误的
20 //            return (int) (this.getRadius() - c.getRadius());
21             
22             //正确的
23             if(this.getRadius() > c.getRadius()) {
24                 return 1;
25             }else if(this.getRadius() < c.getRadius()) {
26                 return -1;
27             }else {
28                 return 0;
29             }
30         }else {
31             return 0;
32             //throw new RuntimeException("传入的数据类型不匹配");
33             
34         }
35             
36         
37     }
38 
39     
40 }
 1 package com.bytezreo.interfacetest;
 2 
 3 public class Circle {
 4 
 5     private double radius;
 6 
 7     public double getRadius() {
 8         return radius;
 9     }
10 
11     public void setRadius(double radius) {
12         this.radius = radius;
13     }
14 
15     public Circle() {
16         super();
17     }
18 
19     public Circle(double radius) {
20         super();
21         this.radius = radius;
22     }
23     
24     
25     
26 }
1 package com.bytezreo.interfacetest;
2 
3 public interface CompareObject {
4 
5     //若返回值是 0代表相等;  若为正数,代表当前对象大; 负数代表当前对象小
6     public int compareTo(Object o);
7     
8 }

Java    接口:比较对象的大小

 

上一篇:圆角边框+盒子阴影+文字阴影


下一篇:Radius协议-学习