如何在compareTo()方法中实现特定的标准

时间:2014-10-15 07:54:09

标签: java compareto

驱动:

public static void main(String[] args) {
    Circle c1 = new Circle(1, "BLUE", true);
    Circle c2 = new Circle(2, "BLUE", true);
    Circle c3 = new Circle(3, "BLUE", false);
    Circle c4 = new Circle(4, "BLACK", true);

    System.out.println("c1 ? c1 " + c1.compareTo(c1));
    System.out.println("c1 ? c2 " + c1.compareTo(c2));
    System.out.println("c1 ? c3 " + c1.compareTo(c3));
    System.out.println("c1 ? c4 " + c1.compareTo(c4));

    Rectangle r1 = new Rectangle(1, 1, "BLUE", true);
    Rectangle r2 = new Rectangle(2, 2, "RED", true);
    Rectangle r3 = new Rectangle(4, 4, "GREEN", false);
    Rectangle r4 = new Rectangle(4, 4, "GREEN", true);

    System.out.println("r1 ? r2 " + r1.compareTo(r2));
    System.out.println("r1 ? r2 " + r1.compareTo(r2));
    System.out.println("c1 ? r2 " + c1.compareTo(r2));
    System.out.println("r3 ? r4 " + r3.compareTo(r4));

}

GeometricObject:

public int compareTo(GeometricObject otherfigure) {
    if (this.getArea() == otherfigure.getArea()) {
        return 0;
    } else if (this.getArea() > otherfigure.getArea()) {
        return 1;
    }
    return -1;

}

现在我只能根据区域进行比较,我不确定如何将下面列出的其他两个标准添加到我的方法中。

如果对象是圆形而蓝色是否大于任何其他对象而不考虑区域,如何添加条件,如果对象是透明的(填充=假),那么它只贡献其面积的50%?

2 个答案:

答案 0 :(得分:0)

要满足要求II,我会向GeometricObject添加一个方法,如colorDependentArea()

public int colorDependentArea(){
       if(!this.filled){
           return this.area/2;
       }else{ 
           return this.area;
       }

}

并在比较中使用此方法而不是getArea()。

public int compareTo(GeometricObject otherfigure) {
    if (this.colorDependentArea() == otherfigure.colorDependentArea()) {
        return 0;
    } else if (this.colorDependentArea() > otherfigure.colorDependentArea()) {
        return 1;
    }
    return -1;

}

答案 1 :(得分:0)

您可以使用derivedArea = area * (filled?1.0:0.5)

考虑透明度

如果您想以某种特定方式对待圈子,可以将检查添加到compareTo方法:

if(this instanceOf Circle && this.isBlue()){
     if(!(otherfigure instanceOf Circle && otherfigure.isBlue()){
         return +1;
     } else {
         // fall back to default behaviour if both object blue circles
     }
} else if (otherfigure instanceOf Circle && otherfigure.isBlue()){
     return -1;
}